Pivot Cross Tabulation Monthly Sales

Transform rows to columns for a monthly sales cross tabulation using conditional aggregation as a pivot technique.

SqlData Integrity

Code

sqlsnippet
10 lines
SELECT
  product_id,
  SUM(CASE WHEN EXTRACT(MONTH FROM sale_date) = 1 THEN quantity ELSE 0 END) AS jan,
  SUM(CASE WHEN EXTRACT(MONTH FROM sale_date) = 2 THEN quantity ELSE 0 END) AS feb,
  SUM(CASE WHEN EXTRACT(MONTH FROM sale_date) = 3 THEN quantity ELSE 0 END) AS mar,
  SUM(CASE WHEN EXTRACT(MONTH FROM sale_date) = 4 THEN quantity ELSE 0 END) AS apr
FROM sales
WHERE EXTRACT(YEAR FROM sale_date) = 2026
GROUP BY product_id
ORDER BY product_id;

Inside the snippet

What runs is SELECT, with sale_date and sales as the object involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Using it

Run the statement against the sale_date table.

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`sale_date`, `sales` — referenced directly, no join needed.