// SQL snippet

Unpivot columns to rows

A SELECT per column, glued with UNION ALL, is the unpivot that works everywhere.

Main statement
All engines

The task

A report table has one column per status. Before you can join it back to orders or chart it properly, you need one row per status again.

The snippet

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

All engines
WITH pivoted AS (
  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
)
SELECT customer_id, 'shipped'   AS status, shipped_total   AS amount FROM pivoted
UNION ALL
SELECT customer_id, 'pending'   AS status, pending_total   AS amount FROM pivoted
UNION ALL
SELECT customer_id, 'cancelled' AS status, cancelled_total AS amount FROM pivoted
ORDER BY customer_id, status;

작동 방식

Each branch of the UNION ALL picks one column and labels it with a literal, producing the long format directly. UNION ALL (not UNION) keeps every row and skips a pointless deduplication pass. Columns are named in the first branch; the rest follow by position.

Variations

UNPIVOT operator (SQL Server, Oracle)

SQL Server Oracle
WITH pivoted AS (
  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
)
SELECT customer_id, status, amount
FROM pivoted
UNPIVOT (amount FOR status IN
         (shipped_total, pending_total, cancelled_total)) u
ORDER BY customer_id, status;

Questions that come up

Does UNPIVOT drop NULLs?

Yes, the UNPIVOT operator excludes rows where the value column is NULL, which changes the row count (Oracle keeps them with UNPIVOT INCLUDE NULLS). The UNION ALL form keeps them. Note also that UNPIVOT fills status with the column names, such as shipped_total (SHIPPED_TOTAL on Oracle), not the clean labels the UNION ALL branches write.

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.