CUBE Emits All Grouping Subsets
Generate every grouping subset in one CUBE query, separate real nulls from rollup nulls with GROUPING, and compare with GROUPING SETS.
Code
-- CUBE:为分组列的每个子集都产出一行小计
SELECT
region,
channel,
SUM(amount) AS total,
COUNT(*) AS orders
FROM sales
GROUP BY CUBE (region, channel)
ORDER BY region NULLS LAST, channel NULLS LAST;
-- GROUPING() 区分“真实 NULL”和“汇总产生的 NULL”
SELECT
region,
channel,
GROUPING(region) AS region_rollup,
GROUPING(channel) AS channel_rollup,
SUM(amount) AS total
FROM sales
GROUP BY CUBE (region, channel)
HAVING GROUPING(region) = 0 OR GROUPING(channel) = 0
ORDER BY region_rollup, region, channel_rollup, channel;
-- 两列 CUBE 等价于显式列出四组 GROUPING SETS
SELECT region, channel, SUM(amount) AS total
FROM sales
GROUP BY GROUPING SETS ((region, channel), (region), (channel), ())
ORDER BY 1 NULLS LAST, 2 NULLS LAST;What the code does
The file runs SELECT statements, touching sales.
Breaking the statements into their working parts: COUNT, 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.
Statements that matter
SELECT
region,
channel,
GROUPING(region) AS region_rollup,
GROUPING(channel) AS channel_rollup,
SUM(amount) AS total
FROM sales
GROUP BY CUBE (region, channel)
HAVING GROUPING(region) = 0 OR GROUPING(channel) = 0
ORDER BY region_rollup, region, channel_rollup, channel;
SELECT
region,
channel,
SUM(amount) AS total,
COUNT(*) AS orders
FROM sales
GROUP BY CUBE (region, channel)
ORDER BY region NULLS LAST, channel NULLS LAST;
SELECT region, channel, SUM(amount) AS total
FROM sales
GROUP BY GROUPING SETS ((region, channel), (region), (channel), ())
ORDER BY 1 NULLS LAST, 2 NULLS LAST;
Interactive Tools for This Topic
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.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.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
- Name the tables involved in this file.
- `sales` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.