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.

SqlData Fetching

Code

snippet
-- 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 WHERE runs too early.

Applying it

The totals table is the working surface here.

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
The references are `totals`.