GROUPING SETS Multi Level Totals
One query yields detail rows, region subtotals, and a grand total via GROUPING SETS, with GROUPING() flagging which output columns are aggregated placeholders.
Code
-- GROUPING SETS: one query emits detail rows, regional subtotals, and a grand total together
SELECT
region,
channel,
SUM(revenue) AS revenue,
-- GROUPING(region)=1 marks region as an aggregation placeholder, not a detail value
GROUPING(region) AS is_region_rollup,
GROUPING(channel) AS is_channel_rollup
FROM sales
GROUP BY GROUPING SETS (
(region, channel), -- detail grain
(region), -- one subtotal row per region
() -- empty set = grand total
)
ORDER BY
GROUPING(region),
GROUPING(channel),
region,
channel;How the snippet works
At its core this is a single SELECT statement against sales.
Breaking the statements into their working parts: SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.
Applying it
The sales table is the working surface here.
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.
FAQ
- Which relations are involved here?
- `sales`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.