CUME_DIST Percentile Ranking
Rank rows as population shares with CUME_DIST and PERCENT_RANK, where tied rows receive identical values under the same window ordering.
Code
-- CUME_DIST:本行及之前行占分区的累计比例,取值 (0,1]
-- PERCENT_RANK:(rank-1)/(总行数-1),取值 [0,1];并列行共享同一比例值
WITH totals AS (
SELECT * FROM (VALUES
('north', 4200), ('south', 2600), ('east', 1500), ('west', 900)
) AS t(region, revenue)
)
SELECT
region,
revenue,
-- percent_rank 的分子就是 rank-1:两列对照着读
RANK() OVER (ORDER BY revenue DESC) AS rank_no,
CUME_DIST() OVER (ORDER BY revenue DESC) AS revenue_share,
PERCENT_RANK() OVER (ORDER BY revenue DESC) AS relative_rank
FROM totals
ORDER BY revenue DESC;What the code does
At its core this is a single SELECT statement against totals.
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.
Watch out for
- To filter on a window function’s result you need an outer query or CTE; the same-level
WHEREruns too early.
Applying it
The totals table is the working surface here.
Interactive Tools for This Topic
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.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.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
- What relations does the SQL touch?
- The references are `totals`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.