GROUP BY DISTINCT Removes Duplicate Totals
Combine overlapping ROLLUP and GROUPING SETS clauses with PostgreSQL 14 GROUP BY DISTINCT so duplicate subtotal rows collapse cleanly.
Code
CREATE TEMP TABLE ad_spend (
region text NOT NULL,
channel text NOT NULL,
cents integer NOT NULL
);
INSERT INTO ad_spend VALUES
('na', 'search', 100),
('na', 'social', 50),
('eu', 'search', 80);
-- (region) appears twice: once explicitly and once inside ROLLUP(region, channel)
SELECT region, channel, GROUPING(region, channel) AS grp_mask, SUM(cents) AS total_cents
FROM ad_spend
GROUP BY ALL GROUPING SETS ((region), ROLLUP (region, channel))
ORDER BY grp_mask, region, channel;
-- GROUP BY DISTINCT (PG 14+) removes duplicate grouping sets without dropping source rows
SELECT region, channel, GROUPING(region, channel) AS grp_mask, SUM(cents) AS total_cents
FROM ad_spend
GROUP BY DISTINCT GROUPING SETS ((region), ROLLUP (region, channel))
ORDER BY grp_mask, region, channel;Walkthrough notes — GROUP BY DISTINCT Removes Duplicate Totals
The file runs SELECT / INSERT / CREATE statements, touching ad_spend.
ad_spend allocates ephemeral per-connection temporary relations directly inline so external fixtures are unnecessary and everything vanishes on disconnect.
Clause by clause, expect: SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; a DISTINCT qualifier that collapses duplicate rows; NOT NULL qualifiers on the required columns.
Applying it
The file sets up its own scratch surface: it builds the session-local tables it works with (ad_spend), so one full run against a throwaway database is enough.
Statements that matter
SELECT region, channel, GROUPING(region, channel) AS grp_mask, SUM(cents) AS total_cents
FROM ad_spend
GROUP BY DISTINCT GROUPING SETS ((region), ROLLUP (region, channel))
ORDER BY grp_mask, region, channel;
SELECT region, channel, GROUPING(region, channel) AS grp_mask, SUM(cents) AS total_cents
FROM ad_spend
GROUP BY ALL GROUPING SETS ((region), ROLLUP (region, channel))
ORDER BY grp_mask, region, channel;
CREATE TEMP TABLE ad_spend (
region text NOT NULL,
channel text NOT NULL,
cents integer NOT NULL
);
Interactive Tools for This Topic
FAQ
- Which objects does the SQL touch?
- `ad_spend`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.