27. Customers above average order volume
Asked in screens shaped like: Amazon, DoorDash, Uber
CRM wants customers whose completed order count is strictly above the average completed-order count across customers who have at least one completed order. Return customer_id and completed_orders, highest volume first.
Requirements
- Columns: customer_id, completed_orders
- Only status = completed
- Keep customers whose count > AVG(count) over customers with a completed order
- Order by completed_orders descending, then customer_id
Expected output
customer_id, completed_orders
Row order is graded, so ORDER BY matters here.
Tables this problem reads. The full warehouse is available in thesandbox.
orders
~200 rows
Order headers. One row per order, so amount is the order total — not a line total.
- order_idINTEGER— 1000–1199
- customer_idTEXT— C01–C12
- countryTEXT— US, DE, IN, UK, BR
- amountREAL
- statusTEXT— 'completed' or 'cancelled'
- ordered_atTEXT— YYYY-MM-DD HH:MM:SS
Pick a warehouse dialect above the editor. The engine is still SQLite; common syntax is rewritten before it runs.
SQLite cheat sheet
- Truncate to day
DATE(ordered_at) - Current date
DATE('now') - Conditional
CASE WHEN … THEN … ELSE … END - String aggregate
GROUP_CONCAT(col, ", ") - JSON field
json_extract(payload, '$.source') - Date difference
JULIANDAY(a) - JULIANDAY(b) - Filter a window
CTE, then WHERE rn = 1 - Median
ROW_NUMBER + COUNT(*) OVER ()
Revealed one at a time. The reference query stays in the Solution tab.
Hint 1
Inner query: per-customer completed counts, then AVG of those counts.
Hint 2
HAVING COUNT(*) > (that average). Do not compare to AVG of all order rows.
SELECT customer_id, COUNT(*) AS completed_orders
FROM orders
WHERE status = 'completed'
GROUP BY customer_id
HAVING COUNT(*) > (
SELECT AVG(cnt)
FROM (
SELECT COUNT(*) AS cnt
FROM orders
WHERE status = 'completed'
GROUP BY customer_id
)
)
ORDER BY completed_orders DESC, customer_id;Why it works
The average is of per-customer counts, not of order amounts. Nested aggregation is the whole point of the screen — a single AVG(amount) is a different metric.
Run your query to see the result set.
Submit to run the checks.
Why it works
The average is of per-customer counts, not of order amounts. Nested aggregation is the whole point of the screen — a single AVG(amount) is a different metric.
Pro problem
Hard problems unlock with Pro
Easy pads stay free. Medium and hard SQL and Python problems — editor, tests, hints, and solutions — open after you upgrade to Pro or coaching.
See plansPractice free easy problems