Find above-average customer spending

Calculate total_spent for every customer from all their orders, treating no orders or all-NULL amounts as 0. Return customer_id, name and total_spent only for customers whose total_spent is strictly above the average of these customer totals. Include zero-spend customers in that average. Row order does not matter. A subquery or CTE is fine.

Difficulty: intermediate

Show hint

First build one total per customer with LEFT JOIN and COALESCE. Then compare each total against AVG of that same set of customer totals.

Tables and sample data

Each test starts with fresh tables. Result rows may be returned in any order. Column names and column order must match.

Sample data: customers
customer_id (integer)name (text)city (text)
1AshaKathmandu
2BenLondon
3ChenSingapore
Sample data: orders
order_id (integer)customer_id (integer)amount (numeric)status (text)region (text)
11100paidEast
21200paidEast
3260pendingWest
Expected sample result
customer_idnametotal_spent
1Asha300

Your solution

SQL · PostgreSQL

Results

PostgreSQL loads when you Run or Submit. Write one read-only SELECT or WITH query. Your query runs in this browser.

Back to Lesson