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.
Code
-- 帧排除子句(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-levelWHEREwill not work — use an outer query or a CTE.
Using it
The scores table is the working surface here.
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables appear in this script?
- `scores` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.