3つのテーブルがあります
country_table
:id int, country_name string
_city_table
:id int, city_name string, postal_code int, country_id int
_customer_table
:id int, customer_name string, city_id id, customer_address string
_私はすべての都市の平均顧客数よりも多くの都市を顧客に返す答えを探しています。そのような都市ごとに、国名、都市名、顧客数を返します。
出力はしてください
country_name, city_name, count
_
サブクエリを使用しようとしましたが、エラーが発生しました
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
_
あらゆる助けが高く評価されています
with table1 as
(
select country_id, city_name, count(city_name) no_of_customers
from city inner join customer
on city.id=customer.city_id
group by city_name, country_id
)
select country_name, city_name, no_of_customers
from table1 inner join country
where no_of_customers >
(
select count(*)/count(distinct city_id) from customer
)
order by country_name;
_
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
)
_
副問合せはさらに短くなることがあります。
Select count(*) / count(distinct city_id) from customer
_