SQL Dojo
Pattern

Pivot and conditional aggregation

Turn the values of a column into columns, such as orders per status side by side, with one SUM(CASE …) each; and back to rows with UNION ALL.

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;
yearordersdeliveredcancelled
2024129112911291
2025120912091209
Try it in Randori

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;
yearordersdeliveredcancelled
20241291110879
2025120996670
Try it in Randori