Rows to Columns: Pivot and Unpivot
GROUP BY cust_id, status returns one row per customer and status. Reports more often need one row per customer with the order counts per status side by side as columns. Spreading row values into columns is a pivot, and the reverse is an unpivot.
| Method | Oracle | PostgreSQL | SQL Server |
|---|---|---|---|
CASE conditional aggregation | O | O | O |
aggregate FILTER (WHERE …) | Works in the sandbox | O | X |
PIVOT / UNPIVOT | O | X | O |
Unpivot with CROSS JOIN + VALUES | O | O | O |
CASE conditional aggregation
Write aggregate(CASE WHEN condition THEN value END) for each column. Rows that do not match the condition become NULL, and aggregate functions skip NULLs, so only matching rows are aggregated. The same statement works on all three DBs, so this is the default method.
Order count by customer and status
SELECT cust_id,
SUM(CASE WHEN status = 'DONE' THEN 1 ELSE 0 END) AS done,
SUM(CASE WHEN status = 'PAID' THEN 1 ELSE 0 END) AS paid,
SUM(CASE WHEN status = 'CANCELED' THEN 1 ELSE 0 END) AS canceled,
COUNT(*) AS total
FROM orders
WHERE cust_id BETWEEN 101 AND 105
GROUP BY cust_id
ORDER BY cust_id
status has only three values, so done + paid + canceled equals total. Amounts are computed with SUM(CASE WHEN … THEN amt END). Without ELSE, a customer with no matching rows gets NULL rather than 0, so use ELSE 0 when 0 is needed.
Amount by customer and status
SELECT cust_id,
SUM(CASE WHEN status = 'DONE' THEN amt END) AS done_amt,
SUM(CASE WHEN status = 'CANCELED' THEN amt END) AS canceled_amt,
SUM(CASE WHEN status = 'CANCELED' THEN amt ELSE 0 END) AS canceled_amt0
FROM orders
WHERE cust_id BETWEEN 101 AND 105
GROUP BY cust_id
ORDER BY cust_id
FILTER (WHERE …)
PostgreSQL supports the standard aggregate FILTER (WHERE condition). The result is the same as CASE, and the condition sits outside the aggregate, which makes it easier to read. It also works in this site's Oracle 23ai sandbox, where COUNT(*) FILTER (…) returns the same count as SUM(CASE …). SQL Server gives a syntax error.
PostgreSQL, Oracle · Conditional aggregation with FILTER
SELECT cust_id,
COUNT(*) FILTER (WHERE status = 'DONE') AS done,
SUM(CASE WHEN status = 'DONE' THEN 1 ELSE 0 END) AS done_case,
SUM(amt) FILTER (WHERE status = 'DONE') AS done_amt
FROM orders
WHERE cust_id BETWEEN 101 AND 105
GROUP BY cust_id
ORDER BY cust_id
PIVOT syntax: Oracle, SQL Server
Oracle and SQL Server have a PIVOT operator. One column is created for each value in FOR column IN (value list), and all remaining columns of the source, other than the aggregated column and the FOR column, become the grouping criteria. So keep only the needed columns in an inline view before pivoting. If ord_id remains in the source, one row comes out per order and no pivot happens.
Oracle · Oracle PIVOT
SELECT *
FROM (SELECT cust_id, status, amt FROM orders WHERE cust_id BETWEEN 101 AND 105)
PIVOT (COUNT(*) AS cnt, SUM(amt) AS amt
FOR status IN ('DONE' AS done, 'PAID' AS paid, 'CANCELED' AS canceled))
ORDER BY cust_id
Oracle accepts several aggregates, and the column names become valuealias_aggregatealias (DONE_CNT, DONE_AMT, …).
SQL Server · SQL Server PIVOT
SELECT cust_id, [DONE], [PAID], [CANCELED]
FROM (SELECT cust_id, status, ord_id FROM orders WHERE cust_id BETWEEN 101 AND 105) s
PIVOT (COUNT(ord_id) FOR status IN ([DONE], [PAID], [CANCELED])) p
ORDER BY cust_id
SQL Server's PIVOT takes only one aggregate and does not accept COUNT(*), so it counts with COUNT(column). The value list consists of bracketed identifiers; omitting the source inline view's alias (s) gives Msg 156, and omitting the alias after PIVOT (…) (p) gives a Msg 102 syntax error. PostgreSQL has no PIVOT syntax.
The limit of pivoting: the column list is fixed in advance
The result columns of a SQL statement must be determined before execution. So whether with CASE or PIVOT, the values to spread must be written directly in the statement. Using a subquery, as in Oracle's PIVOT … IN (SELECT DISTINCT status FROM orders), gives an ORA-00936 error.
- When a new status value appears, it shows up in no column until the statement is changed. With the
CASEmethod, keepingCOUNT(*) AS totalalongside lets you notice it because the sum no longer matches. - If the values change often, read the list first with
SELECT DISTINCT statusand build the statement in the application (dynamic SQL), or pivot on the screen and have SQL return the vertical result ofGROUP BY cust_id, status.
Pivot + ROLLUP: a totals row
CASE conditional aggregation is ordinary aggregation, so it can be used with ROLLUP. A row with per-column totals is appended at the end.
Order count by status with a totals row
SELECT CASE WHEN GROUPING(cust_id) = 1 THEN '(TOTAL)'
ELSE CAST(cust_id AS VARCHAR(10)) END AS cust_label,
SUM(CASE WHEN status = 'DONE' THEN 1 ELSE 0 END) AS done,
SUM(CASE WHEN status = 'PAID' THEN 1 ELSE 0 END) AS paid,
SUM(CASE WHEN status = 'CANCELED' THEN 1 ELSE 0 END) AS canceled,
COUNT(*) AS total
FROM orders
WHERE cust_id BETWEEN 101 AND 105
GROUP BY ROLLUP(cust_id)
ORDER BY GROUPING(cust_id), cust_id
The label column holds both the numeric cust_id and the string '(TOTAL)', so CAST converts it to a string.
Unpivot: columns to rows
This turns a table with quarterly columns (q1, q2, q3) into (id, quarter, value) rows. In the table below, id 1 is (10, 20, NULL) and id 2 is (30, NULL, 40).
The most portable method is to build the list of column names with VALUES, CROSS JOIN it, and pick the value of the corresponding column with CASE. Each source row is duplicated as many times as there are columns. Chaining one SELECT per column with UNION ALL gives the same result, but the source is repeated in the statement as many times as there are columns.
Unpivot with CROSS JOIN VALUES
WITH wide AS (
SELECT * FROM (VALUES (1, 10, 20, NULL), (2, 30, NULL, 40)) t(id, q1, q2, q3)
)
SELECT w.id, k.qtr,
CASE k.qtr WHEN 'Q1' THEN w.q1 WHEN 'Q2' THEN w.q2 WHEN 'Q3' THEN w.q3 END AS amt
FROM wide w
CROSS JOIN (VALUES ('Q1'), ('Q2'), ('Q3')) k(qtr)
ORDER BY w.id, k.qtr
The result is 6 rows, and NULL cells remain as rows. PostgreSQL references the source row's columns directly inside VALUES with LATERAL, and SQL Server does the same with CROSS APPLY. In the Oracle 23ai sandbox, referencing an outer column inside VALUES is an error (ORA-00904).
PostgreSQL · Unpivot with LATERAL VALUES
WITH wide AS (
SELECT * FROM (VALUES (1, 10, 20, NULL), (2, 30, NULL, 40)) t(id, q1, q2, q3)
)
SELECT w.id, v.qtr, v.amt
FROM wide w
CROSS JOIN LATERAL (VALUES ('Q1', w.q1), ('Q2', w.q2), ('Q3', w.q3)) v(qtr, amt)
ORDER BY w.id, v.qtr
SQL Server · Unpivot with CROSS APPLY VALUES
WITH wide AS (
SELECT * FROM (VALUES (1, 10, 20, NULL), (2, 30, NULL, 40)) t(id, q1, q2, q3)
)
SELECT w.id, v.qtr, v.amt
FROM wide w
CROSS APPLY (VALUES ('Q1', w.q1), ('Q2', w.q2), ('Q3', w.q3)) v(qtr, amt)
ORDER BY w.id, v.qtr
UNPIVOT in Oracle and SQL Server drops NULL cells. The two statements below return 4 rows. Oracle can keep NULL cells with UNPIVOT INCLUDE NULLS.
Oracle · Oracle UNPIVOT
WITH wide AS (
SELECT * FROM (VALUES (1, 10, 20, NULL), (2, 30, NULL, 40)) t(id, q1, q2, q3)
)
SELECT *
FROM wide
UNPIVOT (amt FOR qtr IN (q1 AS 'Q1', q2 AS 'Q2', q3 AS 'Q3'))
ORDER BY id, qtr
SQL Server · SQL Server UNPIVOT
WITH wide AS (
SELECT * FROM (VALUES (1, 10, 20, NULL), (2, 30, NULL, 40)) t(id, q1, q2, q3)
)
SELECT id, qtr, amt
FROM wide
UNPIVOT (amt FOR qtr IN (q1, q2, q3)) u
ORDER BY id, qtr
In SQL Server, the qtr values are the column names as is (q1, q2, q3); Oracle can set the values separately with AS 'Q1'.
TIP If unpivoting is needed often, suspect the table design. A table that spreads quarters, months, or items into columns must change its columns every time a value is added. Storing in a vertical (id, quarter, value) structure and pivoting for display holds up better to change.