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 date
2 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 group
4 SUM(total) AS revenue
5FROM
6 orders
-- One group per (year, month) pair, so January 2024 and January 2025 stay separate
7GROUP BY
8 YEAR(order_date),
9 MONTH(order_date)
-- Sort chronologically: by year, then by month
10ORDER BY
11 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

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

More SQL examples at level 4

← SQL typing practice