← 中文资源

简体中文版本

ROLLUP 生成层级小计

用 ROLLUP 聚合销售额,得到地区与月份小计以及总计,并用 GROUPING 标记汇总行。

阅读英文原文

实现说明

一个文件里不止一条语句:SELECT / INSERT / CREATE,sales 都在涉及之列。 从子句角度看,用到了:用 SUM 做聚合;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定。

常见问题

这个文件引用了哪些表?

sales——这些名字在文件里直接引用,不涉及连接。

核心语句

SELECT region,
       month,
       sum(amount) AS total,
       GROUPING(region) AS region_is_total,
       GROUPING(month) AS month_is_total
FROM sales
GROUP BY ROLLUP (region, month)
ORDER BY region NULLS LAST, month NULLS LAST;
SELECT region, month, sum(amount) AS total
FROM sales
GROUP BY GROUPING SETS ((region, month), (region), ())
ORDER BY region NULLS LAST, month NULLS LAST;
INSERT INTO sales (region, month, amount)
VALUES
  ('north', '2026-01-01', 120.00),
  ('north', '2026-02-01', 80.00),
  ('south', '2026-01-01', 200.00),
  ('south', '2026-02-01', 50.00);

代码示例

CREATE TABLE sales (
  region text NOT NULL,
  month date NOT NULL,
  amount numeric(10, 2) NOT NULL
);

INSERT INTO sales (region, month, amount)
VALUES
  ('north', '2026-01-01', 120.00),
  ('north', '2026-02-01', 80.00),
  ('south', '2026-01-01', 200.00),
  ('south', '2026-02-01', 50.00);

SELECT region,
       month,
       sum(amount) AS total,
       GROUPING(region) AS region_is_total,
       GROUPING(month) AS month_is_total
FROM sales
GROUP BY ROLLUP (region, month)
ORDER BY region NULLS LAST, month NULLS LAST;

-- ROLLUP expands to these grouping sets.
SELECT region, month, sum(amount) AS total
FROM sales
GROUP BY GROUPING SETS ((region, month), (region), ())
ORDER BY region NULLS LAST, month NULLS LAST;