I had a fairly straightforward interview question: return all countries that have more customers than the average number of customers of all cities.
country table:
id country_name
1 Austria
2 Germany
3 United Kingdom
city table:
id city_name country_id
1 Wien 1
2 Berlin 2
3 Hamburg 2
4 London 3
customer table:
id customer_name city_id
1 cust1 1
2 cust2 4
3 cust3 3
4 cust4 1
5 cust5 2
6 cust6 1
7 cust7 4
8 cust8 2
Below is my solution. My answer was close but didn't pass the test case because mine returned more countries than the expected output. Do you know why, or how would you approach this problem?
SELECT
co.country_name, COUNT(customer_name)
FROM
country co
JOIN
city ci ON co.id = ci.country_id
JOIN
customer cu ON ci.id = cu.city_id
GROUP BY co.country_name
HAVING COUNT(customer_name) > (SELECT
AVG(temp.cnt)
FROM
(SELECT
ci.id, COUNT(customer_name) AS cnt
FROM
city ci
JOIN customer cu ON ci.id = cu.city_id
GROUP BY ci.id) temp)
ORDER BY co.country_name ASC;
Users in this thread SQL: Count values higher than average for a group are using WHERE instead of HAVING to select value bigger than average. I wonder if HAVING is not suitable for this type of problem.