Pivot Cross Tabulation Monthly Sales
Transform rows to columns for a monthly sales cross tabulation using conditional aggregation as a pivot technique.
Code
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which objects does the SQL touch?
- `sale_date`, `sales` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.