【问题标题】:SQL Query: Number of Districts each Country has? [closed]SQL 查询:每个国家有多少个区? [关闭]
【发布时间】:2016-10-21 14:13:40
【问题描述】:

尝试编写一个查询,该查询将提供国家名称和该国家拥有的地区数量,并按结果排序 从最高到最低的地区数量。问题是我无法弄清楚如何具体计算每个国家的地区数量,最终得到一个国家旁边的地区总数,仅此而已......

这两个表是 Country(包含 Name、Code)和 City(包含 Name、District、CountryCode)。

Country.Code 和 City.CountryCode 相同,这就是这两个表的共同点。

非常感谢您的帮助!

【问题讨论】:

  • JOIN 表格,做一个GROUP BY,使用COUNT(*)

标签: mysql sql country


【解决方案1】:
 SELECT Name, noofdistricts
   FROM 
      (  SELECT c.Name,COUNT( ci.District ) AS noofdistricts
           FROM Country c
           JOIN City ci
             ON c.code = ci.countrycode
          GROUP BY c.Name
       ) Z
 ORDER BY Name,noofdistricts DESC
 ;  

【讨论】:

  • 我错过了 group by 声明。我如何进一步按 noofdistricts 降序排列这些结果? Order by 似乎无法与 group by 一起使用
  • 我添加了 order by 子句。请立即检查
  • 这是我逐字逐句的,但仍未排序。虽然看不到问题
  • 现在试试...
  • "每个派生表都必须有自己的别名"
【解决方案2】:

然后做一个JOIN 然后GROUP BY 喜欢

select c.Name,
count(cc.District) as total_district
from country c join city cc on c.code = cc.CountryCode 
group by c.Name
order by total_district desc;

【讨论】:

    【解决方案3】:

    如果我理解正确,您正在寻找这样的东西(根据 City 表中的信息计算一个国家/地区有多少个独特的地区):

    select
      districts.country_name as country_name,
      count(districts.district) as district_count
    from (      
      select unique --we want to count how many unique districts are there in a given country
        country.code as country_code,
        country.name as country_name,
        city.district as district --we want to get districts where cities are located
      from 
        Country country,
        City city
      where city.CountryCode = country.Code --join cities to countries
    ) districts
    group by districts.country_code
    order by district_count desc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      相关资源
      最近更新 更多