mysql - 客户多于平均水平的城市。子查询

标签 mysql sql subquery inner-join having-clause

我有三张 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/

    相关文章:

    php - 使用 Pdo 的 Codeigniter 发出对成员函数 rowCount() 的调用

    sql - 合并oracle或db2中两个表之间的日期范围

    Mysql - 您无法在 FROM 子句中指定要更新的目标表 - 子查询误解?

    caching - 18M+ 行表的子查询和 MySQL 缓存

    SQLite 更新查询 - 带有别名的子查询不起作用

    mysql - 通过Scheme与数据库交互

    php - echo 不起作用,位于 ($row=0)

    c# - 获取调用 CLR 函数的 SQL 语句

    php - 对 mysql 表的间歇性 INSERT 失败

    mysql - 如何使用聚合函数进行左连接?