我有三张 table
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
非常感谢任何帮助
最佳答案
您查询的连接逻辑看起来没问题,但是子查询需要修复。我会这样写:
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 cu1.city_id) from customer cu1
)
笔记:city
子查询中的表;你可以从表customer
中得到你想要的信息只要group by
中添加了主键列条款,为了处理可能的同名城市/国家(在现实生活中,确实发生过)关于mysql - 客户多于平均水平的城市。子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63432969/