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.

SqlData Integrity

Code

snippet
-- 每个学生想知道:去掉自己后,班里其他人的平均分是多少
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-level WHERE will not work — use an outer query or a CTE.

Applying it

Run the statement against the scores table.

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
The references are `scores`.