Hypothetical Set Rank Within Group

rank(8.00) WITHIN GROUP inserts a would-be value into each ordering and reports its rank directly — the same semantics as a window rank without a frame.

SqlData Fetching

Code

snippet
-- 假设集聚合(hypothetical-set):把一个"假如存在"的值插进排序列,直接问名次
CREATE TABLE leaderboard (
    region text NOT NULL,
    player text NOT NULL,
    score  numeric(6,2) NOT NULL
);
INSERT INTO leaderboard VALUES
    ('eu', 'ada', 9.50), ('eu', 'grace', 8.20),
    ('us', 'linus', 7.70), ('us', 'alan', 6.10);

-- 每个赛区各自算一次假设名次:8.00 在 eu 排第 3,在 us 排第 1
SELECT region,
       rank(8.00) WITHIN GROUP (ORDER BY score DESC) AS would_be_rank
FROM leaderboard
GROUP BY region;

-- 全局口径:9.50 与 8.20 都在 8.00 之前,假设名次为 3
SELECT rank(8.00) WITHIN GROUP (ORDER BY score DESC) FROM leaderboard;

What the code does

The file runs SELECT / INSERT / CREATE statements, touching leaderboard.

Breaking the statements into their working parts: a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

Applying it

Run the statement against the leaderboard table.

Statements that matter

SELECT region,
       rank(8.00) WITHIN GROUP (ORDER BY score DESC) AS would_be_rank
FROM leaderboard
GROUP BY region;
INSERT INTO leaderboard VALUES
    ('eu', 'ada', 9.50), ('eu', 'grace', 8.20),
    ('us', 'linus', 7.70), ('us', 'alan', 6.10);
CREATE TABLE leaderboard (
    region text NOT NULL,
    player text NOT NULL,
    score  numeric(6,2) NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`leaderboard` — referenced directly, no join needed.