← All SQL interview questions
Customers who out-spend the average customer
MediumSubqueriesMeeshoMyntra
The loyalty team wants to reward customers whose total spend is above the average total spend of all customers.
From purchases, return customer_name and total_spent for every customer whose total spend is greater than the average of all customer totals. Show the biggest spender first.
Sample data
Table: purchases
15 row(s) · showing first 8
| purchase_idINT | customer_nameTEXT | amountNUMERIC(10,2) |
|---|---|---|
| 1 | Anil | 1200.00 |
| 2 | Anil | 3400.00 |
| 3 | Bela | 800.00 |
| 4 | Bela | 650.00 |
| 5 | Chetan | 5200.00 |
| 6 | Chetan | 4100.00 |
| 7 | Deepa | 1500.00 |
| 8 | Deepa | 2200.00 |
purchases
- purchase_idINT
- customer_nameTEXT
- amountNUMERIC(10,2)
- Step 1: First build per-customer totals in a subquery, then average those totals. `AVG(amount)` over raw rows would give the average purchase, which is a different number.
- Step 2: The average of customer totals here is 5925 (35550 / 6).
- Step 3: The outer query groups again and uses `HAVING SUM(amount) > (subquery)` to keep only the customers above it.
SELECT customer_name,
SUM(amount) AS total_spent
FROM purchases
GROUP BY customer_name
HAVING SUM(amount) > (
SELECT AVG(customer_total)
FROM (SELECT SUM(amount) AS customer_total
FROM purchases
GROUP BY customer_name) AS totals
)
ORDER BY total_spent DESC;More Subqueries questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program