Multi-Column GROUP BY in SQL
Level 4161 keystrokes
GROUP BY can use several columns or expressions; here year and month together give monthly revenue.
SQL code
1SELECT -- YEAR() takes the year from the order date2 YEAR(order_date) AS year, -- MONTH() takes the month number (1-12)3 MONTH(order_date) AS month, -- Add up the order totals of each group4 SUM(total) AS revenue5FROM6 orders-- One group per (year, month) pair, so January 2024 and January 2025 stay separate7GROUP BY8 YEAR(order_date),9 MONTH(order_date)-- Sort chronologically: by year, then by month10ORDER BY11 year,12 month;Output
+------+-------+---------+ | year | month | revenue | +------+-------+---------+ | 2024 | 1 | 5250.00 | | 2024 | 2 | 7800.00 | | 2024 | 3 | 6100.00 | +------+-------+---------+ 3 rows in set
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this SQL code and how often they appear.
(× 5)× 5_× 4,× 4;× 1