实现说明
这条语句是 SELECT,涉及 api_events、gap、timed。
真正干活的子句:先用 WITH … AS 把中间结果命名成 CTE,主查询再引用它;用 COUNT、SUM 做聚合;GROUP BY 把同组行折叠成每个分组一行;窗口函数(OVER (…))逐行取值计算、不把多行压成一行;ORDER BY 固定了输出顺序。
使用要点
- 要按窗口函数的结果过滤,需要外层查询或 CTE;同级
WHERE跑得太早。
常见问题
这段 SQL 会碰到哪些对象?
api_events、gap、timed——直接引用,无需连接。
代码示例
-- Each event's duration = the next event's timestamp minus the current one: LEAD looks one row ahead
-- Window output cannot mix with same-level aggregation, so the outer query does the rollup
WITH api_events (endpoint, occurred_at) AS (
VALUES
('GET /orders', timestamptz '2026-06-01 09:00:00+00'),
('GET /orders', timestamptz '2026-06-01 09:00:00.120+00'),
('GET /orders', timestamptz '2026-06-01 09:00:00.450+00'),
('POST /orders', timestamptz '2026-06-01 09:00:01+00'),
('POST /orders', timestamptz '2026-06-01 09:00:01.300+00')
),
timed AS (
SELECT
endpoint,
occurred_at,
LEAD(occurred_at) OVER (PARTITION BY endpoint ORDER BY occurred_at)
- occurred_at AS gap
FROM api_events
)
SELECT
endpoint,
COUNT(*) AS events,
-- A session's last row has no next row, so its gap is NULL; SUM skips it and the report stays correct
ROUND(SUM(EXTRACT(EPOCH FROM gap))::numeric, 3) AS total_seconds
FROM timed
GROUP BY endpoint
ORDER BY endpoint;