Overview
Find the customers who spend more than the average customer by naming a per-customer step with WITH, and compare against the right average.
- WITH name AS (query)
- Querying a CTE like a table
- Average per customer, not per order
Short Course
WITH name AS (query) gives a step a name you can query like a table, so a
long report becomes readable steps. Trap: "above average" needs the right
average. The average customer's spend is not AVG(total) over orders.
WITH per_city AS (
SELECT city, COUNT(*) AS customers
FROM customers
GROUP BY city
)
SELECT city
FROM per_city
WHERE customers > (SELECT AVG(customers) FROM per_city);
Task
Return the name and total spend of every customer who spent more than the
average customer, highest spend first. In the database below, customers spend
100 on average, while the average order is only 75.
Database
Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.
| idINTEGER | nameTEXT |
|---|---|
| 1 | Ana |
| 2 | Bo |
| 3 | Cy |
| idINTEGER | customer_idINTEGER | totalREAL |
|---|---|---|
| 1 | 1 | 100.0 |
| 2 | 1 | 100.0 |
| 3 | 2 | 90.0 |
| 4 | 3 | 10.0 |
Test Suites
Pending
Next
Output