Pivot and conditional aggregation
A report wants one column per value (per status, per payment method, per year) where the data has one row per value. Write one conditional aggregate per column:
SELECT customer_id,
COUNT(*) AS orders,
SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders
GROUP BY customer_id;
For an amount, SUM(CASE WHEN method = 'card' THEN amount END); for text, MAX(CASE …). The way back, unpivot, turns
a wide table (one column per quarter) into rows: one SELECT per column, glued with UNION ALL.
The trap. COUNT(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) counts every row: COUNT counts what is not
NULL, and 0 is not NULL. Use SUM with ELSE 0, or COUNT with no ELSE. And the values are written by hand: a new
status gets no column until you add it, so check that the columns add up to the total.
On your warehouse. Postgres and DuckDB have the shorter COUNT(*) FILTER (WHERE status = 'cancelled'); BigQuery
writes COUNTIF(…), Snowflake and Databricks COUNT_IF(…). Snowflake, BigQuery and Databricks have
PIVOT (SUM(amount) FOR method IN ('card', 'paypal')) and UNPIVOT; Postgres has neither; DuckDB writes
PIVOT payments ON method USING SUM(amount).
The trap
SELECT EXTRACT(YEAR FROM ordered_at) AS year,
COUNT(*) AS orders,
COUNT(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
COUNT(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders
GROUP BY EXTRACT(YEAR FROM ordered_at)
ORDER BY year;
| year | orders | delivered | cancelled |
|---|---|---|---|
| 2024 | 1291 | 1291 | 1291 |
| 2025 | 1209 | 1209 | 1209 |
The fix
SELECT EXTRACT(YEAR FROM ordered_at) AS year,
COUNT(*) AS orders,
SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders
GROUP BY EXTRACT(YEAR FROM ordered_at)
ORDER BY year;
| year | orders | delivered | cancelled |
|---|---|---|---|
| 2024 | 1291 | 1108 | 79 |
| 2025 | 1209 | 966 | 70 |