SQL 问题:每个国家有多少个地区?

SQL Query: Number of Districts each Country has?

尝试编写一个查询,以提供国家名称和该国家拥有的地区数量,并按 从最高到 lowest.The 的地区数量问题是我无法弄清楚如何具体计算每个国家的地区数量并最终得到一个国家旁边的地区总数,没有别的......

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

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

非常感谢您的帮助!

 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
 ;  

然后做一个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;

如果我没理解错的话,你正在寻找这样的东西(根据城市 table 的信息计算一个国家有多少个独特的地区):

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