实现说明
一个文件里不止一条语句:SELECT / INSERT / CREATE,orders 都在涉及之列。
orders 是这个文件自己建的会话级临时表——建表动作就在文件里,会话一结束它们就消失。
具体组合了这些手段:用 COUNT、AVG、MAX 做聚合;窗口函数(OVER (…))在多行上求值而行的数量不变;ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。
使用要点
- 窗口函数在
WHERE/GROUP BY之后求值,同级WHERE引用不到它的输出——要过滤请套外层查询或 CTE。
常见问题
它引用了哪些表或 CTE?
orders——以名字直接出现在查询里,没有连接环节。
核心语句
SELECT
id,
customer,
total_cents,
count(*) OVER (PARTITION BY customer) AS orders_of_customer,
max(total_cents) OVER (PARTITION BY customer) AS biggest_order,
round(avg(total_cents) OVER (PARTITION BY customer), 1) AS avg_order
FROM orders
ORDER BY customer, id;
INSERT INTO orders VALUES
(1, 'acme', 2500),
(2, 'acme', 1900),
(3, 'acme', 6100),
(4, 'lin', 990),
(5, 'lin', 1200);
CREATE TEMP TABLE orders (
id int PRIMARY KEY,
customer text NOT NULL,
total_cents int NOT NULL
);
代码示例
-- COUNT OVER (PARTITION BY) annotates rows with group aggregates
-- GROUP BY 会塌缩行;窗口聚合给每行标注所在组的汇总
CREATE TEMP TABLE orders (
id int PRIMARY KEY,
customer text NOT NULL,
total_cents int NOT NULL
);
INSERT INTO orders VALUES
(1, 'acme', 2500),
(2, 'acme', 1900),
(3, 'acme', 6100),
(4, 'lin', 990),
(5, 'lin', 1200);
SELECT
id,
customer,
total_cents,
-- 每行都带上本组的订单数与最大单:行数不塌缩
count(*) OVER (PARTITION BY customer) AS orders_of_customer,
max(total_cents) OVER (PARTITION BY customer) AS biggest_order,
round(avg(total_cents) OVER (PARTITION BY customer), 1) AS avg_order
FROM orders
ORDER BY customer, id;