SELECT country, tier, count(*) FROM customers GROUP BY GROUPING SETS ((country, tier), (country), (tier), ());
Set
Meaning
(a, b)
Group by both
(a)
Subtotal by a
()
Grand total
2. Using ROLLUP
SELECT year, quarter, sum(revenue) FROM sales GROUP BY ROLLUP (year, quarter);-- Equivalent to GROUPING SETS ((year,quarter),(year),())
3. Using CUBE
SELECT region, product, sum(revenue) FROM sales GROUP BY CUBE (region, product);-- All 2^n combinations
Construct
Subgroups Generated
ROLLUP(a,b,c)
n+1 levels (hierarchy)
CUBE(a,b,c)
2^n combinations
GROUPING SETS
Explicit list
4. Using GROUPING Function
SELECT coalesce(country,'(all)') AS country, coalesce(tier,'(all)') AS tier, GROUPING(country, tier) AS gid, -- bitmask count(*) FROM customers GROUP BY ROLLUP (country, tier);
GROUPING(col) Returns
Meaning
0
Column is in grouping set
1
Column is aggregated away (subtotal)
5. Combining GROUPING SETS with FILTER
SELECT country, tier, count(*) FILTER (WHERE active), count(*) FILTER (WHERE NOT active) FROM customers GROUP BY GROUPING SETS ((country, tier),(country),());
6. Using Empty Grouping Set
SELECT count(*) FROM orders GROUP BY GROUPING SETS (());
Note:() in grouping sets produces a single grand-total row even when normal GROUP BY would yield none.