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.
Code
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-levelWHEREwill not work — use an outer query or a CTE.
Applying it
Point it at the scores table.
Interactive Tools for This Topic
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.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.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 relations are involved here?
- The references are `scores`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.