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.

SqlData Integrity

Code

sqlsnippet
27 lines
-- 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

FAQ

Name the tables involved in this file.
`sales` — referenced directly, no join needed.