实现说明
这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 readings。
机制上由这些部分组成:用 COUNT 做聚合;窗口函数(OVER (…))逐行取值计算、不把多行压成一行;ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定。
使用要点
- 窗口函数在
WHERE/GROUP BY之后求值,同级WHERE引用不到它的输出——要过滤请套外层查询或 CTE。
常见问题
这段 SQL 涉及哪些关系?
readings。
核心语句
INSERT INTO readings (sensor, taken_at, celsius) VALUES
('a', 1, 21.5), ('a', 2, NULL), ('a', 3, 22.0),
('b', 1, 19.0), ('b', 2, 20.5), ('b', 3, NULL);
CREATE TABLE readings (
sensor text NOT NULL,
taken_at int NOT NULL,
celsius numeric
);
代码示例
-- NULL semantics of window aggregates: COUNT(*) counts every row, COUNT(celsius) counts only non-null values
CREATE TABLE readings (
sensor text NOT NULL,
taken_at int NOT NULL,
celsius numeric
);
INSERT INTO readings (sensor, taken_at, celsius) VALUES
('a', 1, 21.5), ('a', 2, NULL), ('a', 3, 22.0),
('b', 1, 19.0), ('b', 2, 20.5), ('b', 3, NULL);
SELECT sensor,
taken_at,
celsius,
COUNT(*) OVER (PARTITION BY sensor) AS rows_in_partition,
COUNT(celsius) OVER (PARTITION BY sensor) AS non_null_in_partition,
COUNT(celsius) OVER (PARTITION BY sensor ORDER BY taken_at
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS non_null_so_far
FROM readings
ORDER BY sensor, taken_at;