Distribution and Ratios: NTILE, PERCENT_RANK, CUME_DIST

Following the ranks and frames of Window functions, this chapter covers functions that compute where a value sits within the whole. The (VALUES …) t(column) in the examples is syntax that builds a small table inline, and it works on all three DBs.

FunctionResult
NTILE(n)Bucket number (1 to n) after dividing rows into n buckets in sort order
PERCENT_RANK()(RANK - 1) / (total rows - 1). 0 to 1
CUME_DIST()Rows with a value less than or equal to the current value / total rows. Greater than 0 to 1
SUM(x) OVER ()Grand total. The denominator of a ratio

NTILE: dividing into n buckets

NTILE(n) sorts the rows and distributes them into n buckets from the front. If the row count is not divisible by n, the leading buckets each get one extra row, as many as the remainder. Dividing 10 rows into 4 gives a quotient of 2 and a remainder of 2, so the bucket sizes are 3, 3, 2, 2.

10 rows into 4 buckets

SELECT x, NTILE(4) OVER (ORDER BY x) AS bucket
FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) t(x)
ORDER BY x

NTILE divides by row count only, so equal values can land in different buckets. Dividing values 1, 2, 2, 2 with NTILE(2) puts one 2 in bucket 1 and the other two in bucket 2. The order among equal values is not determined, so append a unique column to ORDER BY to fix the result. If there are fewer rows than n, one row goes into each bucket from bucket 1 and the trailing buckets are empty.

Quartiles of customers 101-120 by order count

SELECT cust_id, COUNT(*) AS orders,
       NTILE(4) OVER (ORDER BY COUNT(*) DESC, cust_id) AS quartile
FROM orders
WHERE cust_id BETWEEN 101 AND 120
GROUP BY cust_id
ORDER BY quartile, orders DESC, cust_id

PERCENT_RANK and CUME_DIST

Both functions return a position between 0 and 1, but they count differently. Here is an example with scores 50, 60, 60, 80, 90 (5 rows).

Percent rank and cumulative distribution

SELECT nm, score,
       RANK()         OVER (ORDER BY score) AS rnk,
       PERCENT_RANK() OVER (ORDER BY score) AS pct_rank,
       CUME_DIST()    OVER (ORDER BY score) AS cume_dist
FROM (VALUES ('A', 50), ('B', 60), ('C', 60), ('D', 80), ('E', 90)) t(nm, score)
ORDER BY score, nm
ScoreRANKPERCENT_RANK = (RANK-1)/(5-1)CUME_DIST = (rows less than or equal)/5
50101/5 = 0.2
6021/4 = 0.253/5 = 0.6
8043/4 = 0.754/5 = 0.8
90515/5 = 1

PERCENT_RANK is always 0 on the first row, and equal values use the earlier rank. CUME_DIST counts all equal values, so both rows with 60 get 0.6. For "top 10%", reverse with ORDER BY … DESC and filter with CUME_DIST() <= 0.1.

Ratio to the total

SUM(…) OVER () has no PARTITION BY, so it attaches the grand total to every row. Used on a GROUP BY result, it gives each group's ratio to the total.

Customer ratio by grade

SELECT grade, COUNT(*) AS cnt,
       SUM(COUNT(*)) OVER () AS total,
       ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 2) AS pct
FROM customers
GROUP BY grade
ORDER BY cnt

VIP 1,000, GOLD 9,000, and NORMAL 90,000 customers come out as 1%, 9%, and 90%. In SQL Server, COUNT(*) and its SUM are both integers, so COUNT(*) / SUM(COUNT(*)) OVER () becomes 0. Multiply by 100.0 first to switch to decimal arithmetic.

Oracle has RATIO_TO_REPORT(expr) OVER (), which performs the same calculation. The result is a ratio between 0 and 1.

Oracle · RATIO_TO_REPORT

SELECT grade, COUNT(*) AS cnt,
       RATIO_TO_REPORT(COUNT(*)) OVER () AS ratio
FROM customers
GROUP BY grade
ORDER BY cnt

Date-range totals: RANGE and INTERVAL

ROWS BETWEEN 2 PRECEDING reaches back 2 rows, and RANGE BETWEEN INTERVAL '2' DAY PRECEDING reaches back to rows whose sort value is within 2 days. If there are missing days in the dates, the two results differ. Oracle and PostgreSQL support this syntax.

Oracle, PostgreSQL · 3-row total and 3-day total

SELECT dt, amt,
       SUM(amt) OVER (ORDER BY dt ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)                 AS rows_3,
       SUM(amt) OVER (ORDER BY dt RANGE BETWEEN INTERVAL '2' DAY PRECEDING AND CURRENT ROW) AS range_3d
FROM (VALUES (DATE '2025-01-01', 10), (DATE '2025-01-02', 20), (DATE '2025-01-05', 30),
             (DATE '2025-01-06', 40), (DATE '2025-01-07', 50)) t(dt, amt)
ORDER BY dt

For the January 5 row, rows_3 adds the two preceding rows (the 1st and 2nd) for 60, and range_3d adds only itself, the only row in the 3rd to 5th, for 30.

SQL Server allows only UNBOUNDED and CURRENT ROW with RANGE; a numeric offset such as RANGE BETWEEN 1 PRECEDING … raises Msg 4194, and INTERVAL '2' DAY is a syntax error (Msg 102). Instead, apply the date condition directly with a correlated subquery or CROSS APPLY.

SQL Server · 3-day total (correlated subquery)

WITH sales AS (
  SELECT * FROM (VALUES (CAST('2025-01-01' AS date), 10), (CAST('2025-01-02' AS date), 20),
                        (CAST('2025-01-05' AS date), 30), (CAST('2025-01-06' AS date), 40),
                        (CAST('2025-01-07' AS date), 50)) t(dt, amt)
)
SELECT s.dt, s.amt,
       (SELECT SUM(s2.amt) FROM sales s2
        WHERE s2.dt BETWEEN DATEADD(day, -2, s.dt) AND s.dt) AS range_3d
FROM sales s
ORDER BY s.dt

Applied to orders, this gives "order count and amount over the previous 30 days" for each order. ord_dt has a time component, so 30 days is exactly 30×24 hours.

Oracle, PostgreSQL · Previous 30-day total per order

SELECT ord_id, ord_dt, amt,
       COUNT(*) OVER (ORDER BY ord_dt RANGE BETWEEN INTERVAL '30' DAY PRECEDING AND CURRENT ROW) AS cnt_30d,
       SUM(amt) OVER (ORDER BY ord_dt RANGE BETWEEN INTERVAL '30' DAY PRECEDING AND CURRENT ROW) AS amt_30d
FROM orders
WHERE cust_id = 101
ORDER BY ord_dt

NOTE When RANGE uses an offset, there must be exactly one ORDER BY column, and it must be a number or a date. This is because the range is set by the difference in values, not by row count.

The WINDOW clause: reusing a window definition

When the same OVER (…) appears several times, define it once with WINDOW name AS (…) and reference it with OVER name. The WINDOW clause goes after HAVING and before ORDER BY.

Define once with the WINDOW clause

SELECT nm, score,
       RANK()         OVER w AS rnk,
       PERCENT_RANK() OVER w AS pct_rank,
       CUME_DIST()    OVER w AS cume_dist,
       COUNT(*)       OVER w AS le_cnt
FROM (VALUES ('A', 50), ('B', 60), ('C', 60), ('D', 80), ('E', 90)) t(nm, score)
WINDOW w AS (ORDER BY score)
ORDER BY score, nm

COUNT(*) OVER w uses the default frame (RANGE … CURRENT ROW), so it counts equal scores together and yields 1, 3, 3, 4, 5. This is the numerator of CUME_DIST.

You can also add a frame to a defined window, as in OVER (w ROWS BETWEEN 1 PRECEDING AND CURRENT ROW). If the frame is placed inside the WINDOW definition, that name cannot be used with ranking functions that do not take a frame (ROW_NUMBER, RANK, etc.) (Oracle ORA-03097, SQL Server Msg 4106).

NOTE The WINDOW clause works on all three sandboxes on this site (Oracle 23ai, PostgreSQL 17, SQL Server 2022). PostgreSQL has supported it for a long time; Oracle added it in 21c and SQL Server in 2022. On earlier versions, repeat OVER (…).