For every customer, report where their total spend sits in the distribution of all customers. Return customer_id, total_spend, percent_rank (from PERCENT_RANK()) and cume_dist (from CUME_DIST()), both computed over the whole table ordered by total_spend.
Input Table(s)
customer_spend
| Column | Type | Meaning |
|---|
| customer_id | INT | Customer identifier |
| total_spend | DECIMAL(10,2) | The customer's total spend (never NULL) |
Key: customer_id is the primary key.
Output Contract
Return these columns in this order, one row per customer:
| Column | Rule |
|---|
| customer_id | The customer identifier |
| total_spend | The customer's total spend, unchanged |
| percent_rank | (rank - 1) / (total rows - 1), where rank is the standard RANK() by total_spend ascending; a value in [0, 1]; rounded to 2 decimals |
| cume_dist | (rows with total_spend less than or equal to this row's) / (total rows); a value in (0, 1]; rounded to 2 decimals |
Customers with equal total_spend get the same percent_rank and the same cume_dist.
Sort by total_spend ascending, then by customer_id ascending.
Example
customer_spend
| customer_id | total_spend |
|---|
| 1 | 100.00 |
| 2 | 100.00 |
| 3 | 300.00 |
| 4 | 300.00 |
Expected result:
| customer_id | total_spend | percent_rank | cume_dist |
|---|
| 1 | 100.00 | 0.00 | 0.50 |
| 2 | 100.00 | 0.00 | 0.50 |
| 3 | 300.00 | 0.67 | 1.00 |
| 4 | 300.00 | 0.67 | 1.00 |
The two 100.00 customers share rank 1, so their percent rank is (1 - 1) / 3 = 0, and 2 of the 4 rows are at or below 100.00, giving a cumulative distribution of 0.50. The two 300.00 customers share rank 3, so their percent rank is (3 - 1) / 3, which rounds to 0.67, and all 4 rows are at or below 300.00.
Constraints and Clarifications
-
The table has 1 to 10,000 rows.
-
customer_id
is unique and never
NULL
.
-
total_spend
is a non-negative decimal and never
NULL
.
-
With a single row,
percent_rank
is 0 and
cume_dist
is 1.
-
The ranking covers the whole table; there is no grouping.