实现说明
这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 ad_spend。
ad_spend 是这个文件自己建的会话级临时表——建表动作就在文件里,会话一结束它们就消失。
逐子句看,这些语句使用了:用 SUM 做聚合;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序;DISTINCT 折叠重复行;必填列上的 NOT NULL 限定。
常见问题
这段 SQL 会碰到哪些对象?
ad_spend。
核心语句
SELECT region, channel, GROUPING(region, channel) AS grp_mask, SUM(cents) AS total_cents
FROM ad_spend
GROUP BY DISTINCT GROUPING SETS ((region), ROLLUP (region, channel))
ORDER BY grp_mask, region, channel;
SELECT region, channel, GROUPING(region, channel) AS grp_mask, SUM(cents) AS total_cents
FROM ad_spend
GROUP BY ALL GROUPING SETS ((region), ROLLUP (region, channel))
ORDER BY grp_mask, region, channel;
CREATE TEMP TABLE ad_spend (
region text NOT NULL,
channel text NOT NULL,
cents integer NOT NULL
);
代码示例
CREATE TEMP TABLE ad_spend (
region text NOT NULL,
channel text NOT NULL,
cents integer NOT NULL
);
INSERT INTO ad_spend VALUES
('na', 'search', 100),
('na', 'social', 50),
('eu', 'search', 80);
-- (region) appears twice: once explicitly and once inside ROLLUP(region, channel)
SELECT region, channel, GROUPING(region, channel) AS grp_mask, SUM(cents) AS total_cents
FROM ad_spend
GROUP BY ALL GROUPING SETS ((region), ROLLUP (region, channel))
ORDER BY grp_mask, region, channel;
-- GROUP BY DISTINCT (PG 14+) removes duplicate grouping sets without dropping source rows
SELECT region, channel, GROUPING(region, channel) AS grp_mask, SUM(cents) AS total_cents
FROM ad_spend
GROUP BY DISTINCT GROUPING SETS ((region), ROLLUP (region, channel))
ORDER BY grp_mask, region, channel;