实现说明
核心是一条 SELECT 语句,作用于 scores。
真正干活的子句:先用 WITH … AS 把中间结果命名成 CTE,主查询再引用它;窗口函数(OVER (…))跨行取值求值,每行仍保持独立;ORDER BY 固定了输出顺序。
使用要点
- 窗口函数在
WHERE与GROUP BY之后求值——同级WHERE看不见它的输出。
常见问题
这个脚本里出现了哪些表?
scores——以名字直接引用,不经过连接环节。
代码示例
-- 帧排除子句(PostgreSQL 11+):在帧内再剔除当前行或并列行
-- EXCLUDE CURRENT ROW 剔当前行;EXCLUDE TIES 剔并列但保留当前行;EXCLUDE GROUP 两者都剔
WITH scores AS (
SELECT * FROM (VALUES
('ada', 98), ('grace', 98), ('linus', 95), ('alan', 88)
) AS t(player, points)
)
SELECT
player,
points,
ARRAY_AGG(player ORDER BY player) OVER (ORDER BY points DESC) AS frame_all,
ARRAY_AGG(player ORDER BY player) OVER (ORDER BY points DESC EXCLUDE CURRENT ROW) AS exclude_self,
ARRAY_AGG(player ORDER BY player) OVER (ORDER BY points DESC EXCLUDE TIES) AS exclude_ties,
ARRAY_AGG(player ORDER BY player) OVER (ORDER BY points DESC EXCLUDE GROUP) AS exclude_group
FROM scores
ORDER BY points DESC, player;