PERCENT_RANK Scores Relative Standing

Score how each row ranks with percent_rank, including how ties collapse to the same percentile inside a window ordering.

SqlData Integrity

Code

snippet
WITH scores (player, points) AS (
    VALUES
        ('ada', 90),
        ('bob', 70),
        ('cy', 90),
        ('dee', 50)
)
SELECT
    player,
    points,
    round((percent_rank() OVER (ORDER BY points))::numeric, 2) AS pct_rank,
    rank() OVER (ORDER BY points) AS position
FROM scores
ORDER BY points DESC, player;

-- ada 与 cy 同为 90 分:percent_rank 相同,rank 也并列

What the code does

What runs is SELECT, with scores as the object involved.

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.

What to watch for

  • 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

Point it at the scores table.

Interactive Tools for This Topic

FAQ

Which relations are involved here?
The references are `scores`.