SQL · Level 3 CTEs

SQL WITH Clauses (CTEs)

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

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);

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.

Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.

customers 3 rows
idINTEGERnameTEXT
1Ana
2Bo
3Cy
orders 4 rows
idINTEGERcustomer_idINTEGERtotalREAL
11100.0
21100.0
3290.0
4310.0
solution.sql
Test Suites Pending
Output