Site icon JS Tech Road

SQL code challenge in March 2021

Recently I took a SQL code challenge:

Question:

There are three tables

Return all cities with more customer than average number of customers of all cities. For each such city, return the country name, the city name, the number of customers.

Output should be

country_name, city_name, count

Idea:

My Solution:

Select co.country_name, ci.city_name, count(*) no_customers
from city ci
inner join country co on co.id = ci. country_id
inner join customer cu on cu.city_id = ci.id
group by co.country_id, co.country_name, ci.city_id, ci.city_name
having count(*) > (
    select count(*) / count(distinct cu.city_id) from customer cu
)
Exit mobile version