Pivot Rows Into Columns With CASE

Turn row values into columns with conditional aggregation, producing a wide report without a dedicated pivot operator.

SqlData Integrity

Code

sqlsnippet
10 lines
SELECT
    product_id,
    SUM(CASE WHEN quarter = 'Q1' THEN revenue ELSE 0 END) AS q1,
    SUM(CASE WHEN quarter = 'Q2' THEN revenue ELSE 0 END) AS q2,
    SUM(CASE WHEN quarter = 'Q3' THEN revenue ELSE 0 END) AS q3,
    SUM(CASE WHEN quarter = 'Q4' THEN revenue ELSE 0 END) AS q4
FROM quarterly_sales
WHERE fiscal_year = 2025
GROUP BY product_id
ORDER BY product_id;

Inside the snippet

What runs is SELECT, with quarterly_sales as the object involved.

Clause by clause, expect: a WHERE clause constraining which rows the statement operates on; SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Putting it to use

The quarterly_sales table is the working surface here.

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
The references are `quarterly_sales`.