尝试编写一个查询,该查询将提供该国家/地区的名称以及该国家/地区所拥有的地区数量以及 从最高到最低的地区数量。问题是我无法弄清楚如何具体计算每个国家的地区数量,最终获得一个国家旁边的地区总数,而不是别的...
这两个表是Country(包含Name,Code)和City(包含Name,District,CountryCode)。
Country.Code和City.CountryCode是相同的,这就是两个表的共同点。
非常感谢任何帮助!
答案 0 :(得分:0)
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
;
答案 1 :(得分:0)
然后执行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;
答案 2 :(得分:0)
如果我理解正确,您正在寻找类似的东西(根据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