Pivoting Rows to Columns
Part of the Beyond the Basics section of Coddy's SQL journey — lesson 14 of 27.
Combine conditional aggregation with GROUP BY to turn rows into columns. It's the SQL version of a spreadsheet pivot.
Suppose sales has rows like (month, product, units). To see one row per month with one column per product:
SELECT
month,
SUM(CASE WHEN product = 'A' THEN units ELSE 0 END) AS product_a,
SUM(CASE WHEN product = 'B' THEN units ELSE 0 END) AS product_b
FROM sales
GROUP BY monthThe GROUP BY bucket each SUM(CASE …) sees is the rows for one month; the CASE picks the slice for one product.
Challenge
EasyAvailable tables and columns:
<strong>sales</strong>:<strong>month</strong>,<strong>product</strong>,<strong>units</strong>
Pivot the data so each row is one month with these columns:
monthapples: totalunitsfor product'apples'that monthbananas: same for'bananas'cherries: same for'cherries'total: totalunitsacross all products that month
Return only months whose total is at least 20. Order by month.
Cheat sheet
Use conditional aggregation with GROUP BY to pivot rows into columns:
SELECT
month,
SUM(CASE WHEN product = 'A' THEN units ELSE 0 END) AS product_a,
SUM(CASE WHEN product = 'B' THEN units ELSE 0 END) AS product_b,
SUM(units) AS total
FROM sales
GROUP BY month
HAVING SUM(units) >= threshold
ORDER BY monthEach SUM(CASE …) sums only the rows matching that product within each GROUP BY bucket.
Try it yourself
SELECT month,
-- one SUM(CASE ...) per product, plus total
FROM sales
GROUP BY month
-- filter to months with total >= 20
ORDER BY month
This lesson includes a short quiz. Start the lesson to answer it and track your progress.