实现说明
实际执行的是 SELECT / INSERT / CREATE——tenant_sales 是涉及的对象。
tenant_sales 是这个文件自己建的会话级临时表——建表动作就在文件里,会话一结束它们就消失。
用到的 SQL 构件:用 SUM 做聚合;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定。
常见问题
这段 SQL 涉及哪些关系?
引用的是 tenant_sales。
核心语句
CREATE TEMP TABLE tenant_sales (
tenant text NOT NULL,
region text NOT NULL,
category text,
cents integer NOT NULL
);
INSERT INTO tenant_sales VALUES
('acme', 'east', 'books', 400),
('acme', 'east', NULL, 150),
('acme', 'west', 'books', 600);
代码示例
CREATE TEMP TABLE tenant_sales (
tenant text NOT NULL,
region text NOT NULL,
category text,
cents integer NOT NULL
);
INSERT INTO tenant_sales VALUES
('acme', 'east', 'books', 400),
('acme', 'east', NULL, 150),
('acme', 'west', 'books', 600);
-- tenant sits outside ROLLUP, so no cross-tenant grand total is emitted
SELECT
tenant,
CASE WHEN GROUPING(region) = 1 THEN 'ALL REGIONS' ELSE region END AS region_label,
CASE WHEN GROUPING(category) = 1 THEN 'ALL CATEGORIES'
ELSE COALESCE(category, 'uncategorized') END AS category_label,
GROUPING(region, category) AS rollup_mask,
SUM(cents) AS total_cents
FROM tenant_sales
GROUP BY tenant, ROLLUP (region, category)
ORDER BY tenant, GROUPING(region), region, GROUPING(category), category;