实现说明
实际执行的是 SELECT / INSERT / CREATE——latency_samples、thresholds 是涉及的对象。
latency_samples 是本文件运行时创建的会话级临时表——不用先建表,会话收尾时一并回收。
真正干活的子句:先用 WITH … AS 把中间结果命名成 CTE,主查询再引用它;通过 一个 JOIN 把多张表的行拼到同一个结果里;窗口函数(OVER (…))逐行取值计算、不把多行压成一行;ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。
使用要点
- 窗口函数在
WHERE/GROUP BY之后求值,同级WHERE引用不到它的输出——要过滤请套外层查询或 CTE。
常见问题
它引用了哪些表或 CTE?
引用的是 latency_samples、thresholds,一个 个 JOIN 把它们连起来。
核心语句
CREATE TEMP TABLE latency_samples (
sample_id integer PRIMARY KEY,
latency_ms integer NOT NULL
);
INSERT INTO latency_samples VALUES
(1, 40), (2, 80), (3, 120), (4, 120), (5, 120), (6, 200);
代码示例
CREATE TEMP TABLE latency_samples (
sample_id integer PRIMARY KEY,
latency_ms integer NOT NULL
);
INSERT INTO latency_samples VALUES
(1, 40), (2, 80), (3, 120), (4, 120), (5, 120), (6, 200);
WITH thresholds AS (
SELECT
PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY latency_ms) AS p50_cont,
PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY latency_ms) AS p75_cont
FROM latency_samples
)
SELECT
s.sample_id,
s.latency_ms,
-- CUME_DIST gives all tied 120ms rows the identical cumulative share (5/6)
ROUND(CUME_DIST() OVER (ORDER BY s.latency_ms)::numeric, 3) AS cume_dist,
-- NTILE splits the three tied 120ms rows across different quartile buckets
NTILE(4) OVER (ORDER BY s.latency_ms, s.sample_id) AS quartile_bucket,
t.p50_cont,
t.p75_cont
FROM latency_samples s
CROSS JOIN thresholds t
ORDER BY s.latency_ms, s.sample_id;