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.

SqlData Integrity

Code

snippet
-- 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

FAQ

Which relations are involved here?
`sales`.