Nested Window Calls Fail And CTE Fix
Window calls cannot nest inside one SELECT level: compute the inner ranking in a CTE, then rank that output in the outer query.
Code
CREATE TEMP TABLE scores (
player text PRIMARY KEY,
score int NOT NULL
);
INSERT INTO scores VALUES ('ada', 98), ('grace', 98), ('linus', 95), ('alan', 88);
-- 想对“名次”再排名?直接嵌套窗口调用会报错(nested fails):
-- ERROR: window function calls cannot be nested
-- SELECT RANK() OVER (ORDER BY RANK() OVER (ORDER BY score DESC)) FROM scores;
WITH inner_rank AS (
SELECT player, score,
RANK() OVER (ORDER BY score DESC) AS score_rank
FROM scores
)
-- 修复(fix):第一层窗口在 CTE 里算完,外层对它的输出再做窗口计算
SELECT player, score, score_rank,
RANK() OVER (ORDER BY score_rank) AS rank_of_rank
FROM inner_rank
ORDER BY score_rank;
-- 同类报错:聚合里包窗口函数同样不行
-- SUM(RANK() OVER (...)) → aggregate function calls cannot contain window function calls
DROP TABLE scores;Inside the snippet
The file runs SELECT / INSERT / CREATE statements, touching scores and inner_rank.
scores is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.
Breaking the statements into their working parts: 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; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Points of care
- 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.
Putting it to use
Setup is internal: the session-local tables it queries (scores) are made by the file, so a single complete run against a scratch database suffices.
Core lines
WITH inner_rank AS (
SELECT player, score,
RANK() OVER (ORDER BY score DESC) AS score_rank
FROM scores
)
SELECT player, score, score_rank,
RANK() OVER (ORDER BY score_rank) AS rank_of_rank
FROM inner_rank
ORDER BY score_rank;
CREATE TEMP TABLE scores (
player text PRIMARY KEY,
score int NOT NULL
);
INSERT INTO scores VALUES ('ada', 98), ('grace', 98), ('linus', 95), ('alan', 88);
Interactive Tools for This Topic
FAQ
- What objects does the SQL involve?
- `scores`, `inner_rank` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.