76. Pivot Quarterly Sales into Columns
MediumPivotingconditional aggregationSUMCASE
To turn rows into columns you use conditional aggregation: SUM(CASE WHEN quarter='Q1' THEN amount END) adds up only the Q1 rows and produces NULL (treated as 0 by SUM across the group) for the rest, collapsing one quarter column into four named columns.
Task: the sales table has one row per product per quarter. Pivot it so each product is a single row with its quarterly totals. Return product, q1, q2, q3, q4. Order by product.
Output columns, in order: product, q1, q2, q3, q4.
Tables
Loading schema…
Expected outputrows must come back in this order
Computing expected output…
This is the result for the example data above. On Submit your query is graded against this example plus 4 hidden edge cases — 5test cases in all. A sloppy query that only fits the example won't pass.
SQL· SQLite · runs in your browser
⌘/Ctrl+↵ run · ⇧⌘/Ctrl+↵ submit
Run a query to see its output here.