Partial ROLLUP And Multi-Arg GROUPING Bitmask

Keep tenant unrolled with partial ROLLUP while using multi-argument GROUPING(region, category) bitmasks to tell real NULLs from subtotal rows.

SqlData Fetching

Code

snippet
CREATE TEMP TABLE tenant_sales (
    tenant   text NOT NULL,
    region   text NOT NULL,
    category text,
    cents    integer NOT NULL
);

INSERT INTO tenant_sales VALUES
    ('acme', 'east', 'books', 400),
    ('acme', 'east', NULL,    150),
    ('acme', 'west', 'books', 600);

-- tenant sits outside ROLLUP, so no cross-tenant grand total is emitted
SELECT
    tenant,
    CASE WHEN GROUPING(region) = 1 THEN 'ALL REGIONS' ELSE region END AS region_label,
    CASE WHEN GROUPING(category) = 1 THEN 'ALL CATEGORIES'
         ELSE COALESCE(category, 'uncategorized') END AS category_label,
    GROUPING(region, category) AS rollup_mask,
    SUM(cents) AS total_cents
FROM tenant_sales
GROUP BY tenant, ROLLUP (region, category)
ORDER BY tenant, GROUPING(region), region, GROUPING(category), category;

Runtime walkthrough — Partial ROLLUP And Multi-Arg GROUPING Bitmask

What runs here is SELECT / INSERT / CREATE — tenant_sales are the objects involved.

tenant_sales sets up transient session-local storage inline within this example without requiring prior setup and discards those objects automatically at close.

The SQL constructs in play: SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

Using it

Nothing outside the file is needed: the session-local tables it touches (tenant_sales) are created by the file itself — point it at a scratch database and run the whole thing.

Key statements

CREATE TEMP TABLE tenant_sales (
    tenant   text NOT NULL,
    region   text NOT NULL,
    category text,
    cents    integer NOT NULL
);
INSERT INTO tenant_sales VALUES
    ('acme', 'east', 'books', 400),
    ('acme', 'east', NULL,    150),
    ('acme', 'west', 'books', 600);

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
The references are `tenant_sales`.