// SQL snippet

Pivot rows to columns with CASE

The portable pivot: SUM(CASE WHEN ...) grouped by the row key. No PIVOT operator needed.

Main statement
All engines

The task

Orders have one row per status change, but your report needs one row per customer with shipped, pending and cancelled totals side by side.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT customer_id,
       SUM(CASE WHEN status = 'shipped'   THEN amount ELSE 0 END) AS shipped_total,
       SUM(CASE WHEN status = 'pending'   THEN amount ELSE 0 END) AS pending_total,
       SUM(CASE WHEN status = 'cancelled' THEN amount ELSE 0 END) AS cancelled_total
FROM orders
GROUP BY customer_id
ORDER BY customer_id;

Cómo funciona

Each CASE keeps only the amount of one status and turns the rest into 0, so the grouped SUM adds up each status into its own column. This is plain SQL: it runs on every engine, including the ones without a PIVOT operator. You must list the statuses in the query, which is fine for stable domains and annoying for hundreds of values.

Variations

Counts instead of sums

SELECT customer_id,
       SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) AS shipped_orders,
       SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending_orders
FROM orders
GROUP BY customer_id;

FILTER clause (PostgreSQL, SQLite 3.30+)

PostgreSQL SQLite
SELECT customer_id,
       SUM(amount) FILTER (WHERE status = 'shipped') AS shipped_total,
       SUM(amount) FILTER (WHERE status = 'pending') AS pending_total
FROM orders
GROUP BY customer_id;

Questions that come up

Why not the PIVOT operator?

SQL Server and Oracle have one, but it still requires listing the column values, MySQL and SQLite do not have it at all, and the CASE form is usually easier to read. The PIVOT operator mainly wins when the aggregate expression is long and reused.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.