Cross-tab with row and column totals
Pivot with CASE, then let ROLLUP add the grand-total row in the same scan.
The task
You want the pivoted status totals per customer plus a final row with the totals for each status, without a second query.
The snippet
Written for PostgreSQL. Versions for MySQL and SQLite are under Variations.
SELECT CASE WHEN GROUPING(customer_id) = 1 THEN 'All'
ELSE CAST(customer_id AS varchar(10)) END AS customer,
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
FROM orders
GROUP BY ROLLUP (customer_id)
ORDER BY GROUPING(customer_id), customer_id;
它的運作方式
ROLLUP adds a summary row where customer_id is NULL; GROUPING() returns 1 on that row so you can label it 'All' instead of a blank. The CASE aggregates stay the same, so the totals row sums each status column. Sorting by GROUPING(customer_id) first puts the 'All' row last and keeps customers in numeric order rather than text order. This exact statement also runs on SQL Server and Oracle; SQLite has no ROLLUP, so fall back to a UNION ALL of the detail and total queries.
Variations
MySQL WITH ROLLUP
MySQLSELECT customer_id,
SUM(CASE WHEN status = 'shipped' THEN amount ELSE 0 END) AS shipped_total
FROM orders
GROUP BY customer_id WITH ROLLUP;
Portable totals with UNION ALL (any engine, SQLite included)
SQLiteSELECT CAST(customer_id AS CHAR(10)) AS customer,
SUM(CASE WHEN status = 'shipped' THEN amount ELSE 0 END) AS shipped_total
FROM orders
GROUP BY customer_id
UNION ALL
SELECT 'All',
SUM(CASE WHEN status = 'shipped' THEN amount ELSE 0 END)
FROM orders;
Questions that come up
Why GROUPING() instead of checking for NULL?
A real customer_id could itself be NULL in messy data. GROUPING() distinguishes the rolled-up summary row from a genuine NULL group, so the label is never wrong.
Keep reading
Related on SQLly
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.