InterviewPrepKit

Home / SQL / Advanced Patterns

Pivot Quarterly Sales Into Columns

medium
Solving tips
  • Recognize a pivot: distinct values of one column need to become separate output columns, so reach for one aggregate per target column.
  • Use `SUM(...) FILTER (WHERE ...)` per quarter and wrap it in `COALESCE(..., 0)` so products missing a quarter show 0 instead of NULL.
  • GROUP BY only the row key (product); the quarter is consumed by the FILTER clauses, not the GROUP BY.

Sales are stored one row per product per quarter. Reshape them so each product is a single row with one column per quarter.

Schema

CREATE TABLE sales (
  product  TEXT,
  quarter  TEXT,   -- 'Q1' | 'Q2' | 'Q3' | 'Q4'
  amount   INTEGER
);

Sample data:

productquarteramount
WidgetQ1100
WidgetQ2150
WidgetQ3200
WidgetQ450
GadgetQ180
GadgetQ290
GadgetQ4120

Task

Return one row per product with columns product, q1, q2, q3, q4, where each quarter column is the total amount for that product in that quarter. A product with no rows for a quarter must show 0 in that column. Order by product ascending.

Expected output

productq1q2q3q4
Gadget80900120
Widget10015020050
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.