Window Frame Exclude Ties

Drop peers from window frames with EXCLUDE CURRENT ROW, EXCLUDE TIES, and EXCLUDE GROUP, keeping the current row where TIES does.

SqlData Fetching

Code

sqlsnippet
16 lines
-- 帧排除子句(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;

How it works

At its core this is a single SELECT statement against scores.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Using it

The scores table is the working surface here.

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`scores` — referenced directly, no join needed.