i have to write a query which will 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. order the result by country name ascending.
Output should be
country_name, city_name, count
I tried to use sub query but I got an error
Select country_name, city_name, count(customer_name)
from country
inner join city on city.country_id = country.id
inner join customer on customer.city_id = city.id
where customer_name > (select avg(customer_name)
from customer
inner join customer on customer.city_id = city.id group by id)
group by 1, 2
I then tried
Select country.country_name, city.city_name, count(customer.customer_name)
from country
inner join city on city.country_id = country.id
inner join customer on customer.city_id = city.id
group by country.country_name, city.city_name
having count(customer.customer_name) >
(
Select count(customer.customer_name) / count(city.city_name) as avg_per_city
from city
inner join customer on customer.city_id = city.id
)
but this is also giving error.
your help would be great.
The second query looks almost correct. Since the city id is unique, you don't need to join to the city table when computing the average.
Try this:
Select country.country_name, city.city_name, count(customer.customer_name)
from country
inner join city on city.country_id = country.id
inner join customer on customer.city_id = city.id
group by country.country_name, city.city_name
having count(customer.customer_name) >
(
Select count(customer.customer_name) / count(distinct city_id) as avg_per_city
from customer
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.