A regional expansion team looks for cities that already have both breadth and depth of demand.
From purchase_log, return city, the number of distinct buyers as buyer_count, and total spend as total_spend, keeping only cities that have at least 3 distinct customers and more than 20000 in total spend.
Sample data
Table: purchase_log
18 row(s) · showing first 8
| purchase_idINT | cityTEXT | customer_codeTEXT | amountNUMERIC(10,2) |
|---|---|---|---|
| 1 | Pune | CU-101 | 9500.00 |
| 2 | Pune | CU-102 | 7200.00 |
| 3 | Pune | CU-103 | 6100.00 |
| 4 | Pune | CU-101 | 3400.00 |
| 5 | Jaipur | CU-201 | 18000.00 |
| 6 | Jaipur | CU-201 | 9000.00 |
| 7 | Jaipur | CU-202 | 2500.00 |
| 8 | Kochi | CU-301 | 4000.00 |
purchase_log
- purchase_idINT
- cityTEXT
- customer_codeTEXT
- amountNUMERIC(10,2)
- Step 1: Aggregate the raw purchases to one row per `city` with `GROUP BY city`.
- Step 2: Breadth of demand is the number of unique buyers, so use `COUNT(DISTINCT customer_code)` rather than `COUNT(*)` — a single customer can appear on many rows.
- Step 3: Depth of demand is `SUM(amount)` for the city.
- Step 4: Both thresholds compare aggregated values, so they belong in `HAVING`, not `WHERE`. `WHERE` is evaluated before grouping and cannot see `SUM`/`COUNT`.
- Step 5: Combine the two conditions with `AND` so a city must clear both bars.
SELECT city,
COUNT(DISTINCT customer_code) AS buyer_count,
SUM(amount) AS total_spend
FROM purchase_log
GROUP BY city
HAVING COUNT(DISTINCT customer_code) >= 3
AND SUM(amount) > 20000;Learn the concept first
Stuck on HAVING? These free SQL lessons teach it step by step.
More HAVING questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program