Aggregation and Grouping · Problem 37 of 118

Cities with Many Customers

MediumAggregation and GroupingShop data

City names have inconsistent case. Return city (in lower case) and customers for every city with more than 25 customers, counting the different spellings together. Sort by customers from high to low, then by city.

Hint 1

Group on LOWER(city), the cleaned value, not on city.

Reference solution

SELECT LOWER(city) AS city, COUNT(*) AS customers
FROM customers
GROUP BY LOWER(city)
HAVING COUNT(*) > 25
ORDER BY customers DESC, city;

You can group by an expression. Grouping on LOWER(city) merges Manila, manila and MANILA into one group, exactly like in the cleaning chapter. The wrong version still displays lower-case names but it grouped by the raw spelling first, so groups are smaller and some cities fall below the threshold.