EXCLUDE CURRENT ROW Drops Self From Frame
Remove the current row from its own window frame with EXCLUDE CURRENT ROW, so aggregate comparisons measure peers only and never the row being scored.
Code
-- 每个学生想知道:去掉自己后,班里其他人的平均分是多少
WITH scores (student, points) AS (
VALUES ('alice', 92), ('bruno', 85), ('chen', 78), ('dana', 85)
)
SELECT
student,
points,
-- 默认帧包含当前行:平均分被自己拉偏
ROUND(AVG(points) OVER ()) AS with_self,
-- EXCLUDE CURRENT ROW 把当前行从帧中剔除:纯同伴视角
ROUND(AVG(points) OVER (ORDER BY points
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
EXCLUDE CURRENT ROW)) AS peers_only,
-- GROUPS 模式下 EXCLUDE CURRENT ROW 也只剔当前行:同分的 bruno/dana 互相保留
COUNT(*) OVER (ORDER BY points
GROUPS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
EXCLUDE CURRENT ROW) AS other_rows
FROM scores
ORDER BY points DESC, student;How the snippet works
The statement is SELECT, touching scores.
Concretely, the SQL combines: a CTE (WITH … AS) that names an intermediate result before the main query; COUNT, AVG aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
Caveats
- 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.
Applying it
Run the statement against the scores table.
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 or CTEs does it reference?
- The references are `scores`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.