Menu
Coddy logo textTech

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 month

The GROUP BY bucket each SUM(CASE …) sees is the rows for one month; the CASE picks the slice for one product.

challenge icon

Challenge

Easy

Available 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:

  • month
  • apples: total units for product 'apples' that month
  • bananas: same for 'bananas'
  • cherries: same for 'cherries'
  • total: total units across all products that month

Return only months whose total is at least 20. Order by month.

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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Beyond the Basics