22. Customer spend quartiles Solved
AdvancedHardNTILEbucketssummary per bucket
Rank customers with at least one delivered order by their delivered spend, highest first, and split them into 4 quartiles with ntile(4) (quartile 1 = top spenders; ties broken by customer id). Return per quartile: quartile, customers, min_spend, max_spend. Sort by quartile.
Your answer returns 4 rows with the columns quartile, customers, min_spend, max_spend. Order matters.
The data
The store from the DuckDB playground, running in your browser with DuckDB. Prices are in EUR; the data covers 2024.
customers20 rows
id | INTEGER primary key |
name | VARCHAR |
country | VARCHAR |
currency | VARCHAR EUR, GBP, USD or JPY |
signed_up | DATE |
tags | VARCHAR[] a list: vip, newsletter, b2b, returns-often |
products10 rows
id | INTEGER primary key |
name | VARCHAR |
category | VARCHAR |
price | DECIMAL(10,2) EUR |
specs | STRUCT weight_g INTEGER, color VARCHAR, sizes VARCHAR[] |
orders300 rows
id | INTEGER primary key |
customer_id | INTEGER → customers.id |
placed_at | TIMESTAMP 2024 |
status | ENUM placed, paid, shipped, delivered, returned |
currency | VARCHAR the customer's currency |
order_items576 rows
order_id | INTEGER → orders.id |
product_id | INTEGER → products.id |
quantity | INTEGER |
unit_price | DECIMAL(10,2) EUR |
web_events20,000 rows
event_id | BIGINT |
ts | TIMESTAMP |
session_id | VARCHAR |
customer_id | INTEGER NULL for anonymous visitors |
event_type | VARCHAR page_view, search, add_to_cart, checkout |
page | STRUCT path, referrer |
device | STRUCT browser, mobile BOOLEAN, screen STRUCT(w, h) |
product_ids | INTEGER[] |
load_ms | INTEGER |
fx_rates720 rows
currency | VARCHAR USD, GBP, JPY |
valid_from | TIMESTAMP |
per_eur | DOUBLE units of currency per 1 EUR |
Hints
ntile(4) OVER (ORDER BY spend DESC, customer_id).Common traps
- Without a tie-breaker, customers with equal spend can land in different quartiles on each run.
Solution
WITH spend AS (
SELECT o.customer_id, sum(oi.quantity * oi.unit_price) AS spend
FROM orders o JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'delivered'
GROUP BY o.customer_id
), q AS (
SELECT customer_id, spend, ntile(4) OVER (ORDER BY spend DESC, customer_id) AS quartile FROM spend
)
SELECT quartile, count(*) AS customers, min(spend) AS min_spend, max(spend) AS max_spend
FROM q
GROUP BY quartile
ORDER BY quartile
Free for personal practice. Please don't republish the questions or solutions. See the Playground License Terms.