Per-customer total spend vs their citys average customer spend: return name, city, totalspend for customers strictly…
SQLLevel: IntermediateAbove-average and subqueries
Per-customer total spend vs their citys average customer spend: return name, city, total_spend for customers strictly above their city average.
Table definitions (from the source exercise):
CREATE TABLE customers(customer_id INTEGER PRIMARY KEY, name TEXT, city TEXT, signup_date TEXT, credit_score INTEGER);
CREATE TABLE orders(order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount REAL, rep_id INTEGER, discount REAL);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: Per-customer totals CTE joined to customers, then a window AVG per city, filter outside.
WITH spend AS (
SELECT c.customer_id, c.name, c.city, SUM(o.amount) AS total_spend
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name, c.city
)
SELECT name, city, total_spend
FROM (
SELECT s.*, AVG(total_spend) OVER (PARTITION BY city) AS city_avg
FROM spend s
) x
WHERE total_spend > city_avg;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT