Intermediate Joins · GROUP BY · HAVING
15. High-value repeat buyers
Concept: GROUP BY · HAVINGshow
WHERE filters rows before grouping; HAVING filters groups after aggregation. Conditions on COUNT() or SUM() therefore go in HAVING, and can be combined with AND.
Example (different data):
SELECT category, COUNT(*) AS n FROM products GROUP BY category HAVING COUNT(*) >= 10 AND AVG(price) < 50;
Your task
The loyalty team wants to invite repeat buyers who also spend real money. One big order isn't enough; neither are many tiny ones.
Using completed orders, return customer_id, order_count and total_spent for customers with at least 2 completed orders AND total_spent over 300. Sort by customer_id.
Solution unlocks after 3 more tries
Starting Postgres in your browser…
query.sql
Output
Write a query and press Run Query (Ctrl/⌘ + Enter).