Rank customer spending within signup sources
Your task
Return source, customer_id, spent_cents, and spend_rank for each customer. Count completed amounts only, with zero for customers who never completed an order. Rank higher totals first within each source, giving ties the same rank and leaving no gaps. Sort by source, rank, then customer ID.
Calculate each customer’s total before ranking them so the window sees one row per customer.
Sample data
| id | name | signup_date | source |
|---|---|---|---|
| 1 | Avery | 2025-01-02 | organic |
| 2 | Casey | 2025-01-05 | |
| 3 | Jordan | 2025-01-12 | organic |
| 4 | Morgan | 2025-02-01 | |
| 5 | Riley | 2025-02-10 | social |
| 6 | Sam | 2025-02-20 | organic |
| 7 | Taylor | 2025-03-01 | social |
| 8 | Devon | 2025-02-07 |
Expected output
| source | customer_id | spent_cents | spend_rank |
|---|---|---|---|
| 4 | 5600 | 1 | |
| 2 | 5000 | 2 | |
| 8 | 3100 | 3 | |
| organic | 1 | 6500 | 1 |
| organic | 6 | 1700 | 2 |
| organic | 3 | 0 | 3 |
| social | 5 | 0 | 1 |
| social | 7 | 0 | 1 |
Show a hint
Get customer totals with a LEFT JOIN and apply DENSE_RANK to those totals.
Window functions guide
Keep detail rows while summarizing
GROUP BY would return one row per genre. A window aggregate with PARTITION BY leaves every album in the result and gives each row its genre's average. This makes it easy to compare a row with its peers.
SELECT title, genre, price,
AVG(price) OVER (PARTITION BY genre) AS genre_average
FROM albums;Specify the window order and frame
The ORDER BY inside OVER defines the order of calculation. ROWS defines which neighboring rows contribute. This example adds the current sale to all earlier sales by ID. The last ORDER BY controls the order shown on screen.
SELECT id, quantity,
SUM(quantity) OVER (
ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_quantity
FROM sales
ORDER BY id;Rank first, then filter
Window results are calculated too late for the same SELECT's WHERE clause. Compute a rank in a CTE, then filter the named result. ROW_NUMBER assigns one position per row. RANK gives ties the same position and may leave gaps.
WITH ranked AS (
SELECT title, genre, ROW_NUMBER() OVER (
PARTITION BY genre ORDER BY price, id
) AS position
FROM albums
)
SELECT genre, title FROM ranked WHERE position = 1;Worked solution
WITH spend AS (SELECT c.source,c.id AS customer_id,COALESCE(SUM(o.total_cents),0) AS spent_cents FROM customers c LEFT JOIN shop_orders o ON o.customer_id=c.id AND o.status='completed' GROUP BY c.id,c.source) SELECT source,customer_id,spent_cents,DENSE_RANK() OVER (PARTITION BY source ORDER BY spent_cents DESC) AS spend_rank FROM spend ORDER BY source,spend_rank,customer_id;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
