Find customers who outspend their signup peers
Your task
For each customer who exceeds their source’s average completed spend, return source, customer_id, and spent_cents. Use zero spend for customers with no completed orders when calculating the average. Sort by source then customer ID.
The average for a source includes everyone who signed up, including those with zero completed spending.
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 |
|---|---|---|
| 2 | 5000 | |
| 4 | 5600 | |
| organic | 1 | 6500 |
Show a hint
Build customer totals in the first CTE, then source averages in a second CTE and join the results.
Subqueries and CTEs guide
Use a query as a value
An aggregate without GROUP BY produces one row. A single-column subquery can therefore provide a scalar value for a comparison. Here each price is compared with an average calculated across the whole table.
SELECT title, price
FROM albums
WHERE price < (SELECT AVG(price) FROM albums);Ask whether a related row exists
An EXISTS subquery only needs to produce one row to be true. It refers to a.id from the outer query, so the test is evaluated for the current album. The expression in the inner SELECT is immaterial to the existence test.
SELECT a.title
FROM albums AS a
WHERE EXISTS (
SELECT 1
FROM sales AS s
WHERE s.album_id = a.id AND s.quantity > 1
);Name intermediate results with WITH
A common table expression gives an intermediate query a name for a single statement. Here the CTE summarizes sales before joining them to albums. Read the CTE on its own first, then read the final SELECT to see how the summary is used.
WITH totals AS (
SELECT album_id, SUM(quantity) AS copies
FROM sales
GROUP BY album_id
)
SELECT a.title, COALESCE(t.copies, 0) AS copies
FROM albums AS a
LEFT JOIN totals AS t ON t.album_id = a.id;Worked solution
WITH spend AS (SELECT c.id,c.source,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), benchmarks AS (SELECT source,AVG(spent_cents) AS average_cents FROM spend GROUP BY source) SELECT s.source,s.id AS customer_id,s.spent_cents FROM spend s JOIN benchmarks b ON b.source=s.source WHERE s.spent_cents>b.average_cents ORDER BY s.source,s.id;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
