SQL,从另一个 table 中选择最大值

SQL, choosing maximum values from another table

我花了最后几个小时在这上面。仍然没有找到答案,所以我想我会问。 我有两个 tables:

Country - Code, Name, Populaion.
City - CountryCode, Name, Population. 

外键是响应country.Code的CountryCode。

我试图找到每个国家/地区中人口最多的城市,输出是国家/地区和城市的名称。我知道这可以用 Max() 来完成,但我很难将我的 table 限制为显示所有国家名称并仅显示人口最多的城市的名称。

SELECT country.name, city.name, MAX(city.Population) 
FROM city
LEFT JOIN country
ON city.CountryCode=Country.Code
GROUP BY city.name, country.name, city.population
ORDER BY city.population DESC;

这只提供了所有国家和城市。谁能帮我缩小范围,让它只显示每个国家的名称,但不显示他们最大的城市?

您想先计算每个国家/地区的最大人口数,然后将其与城市 table 相结合,以了解它属于哪个城市。之后,将其与国家 table 合并以获得所需的结果。

select co.name,
    ct.name,
    ct.population
from (
    select c1.*
    from city c1
    join (
        select countryCode,
            max(population) population
        from city
        group by countryCode
        ) c2 on c1.countryCode = c2.countryCode
        and c1.population = c2.population
    ) ct
join country co on ct.countryCode = co.code;

使用左连接查找组中最大值的另一种方法:

select co.name,
    ct.name,
    ct.population
from (
    select c1.*
    from city c1
    left join city c2 on c1.countryCode = c2.countryCode
        and c1.population < c2.population
    where c2.countryCode is null
    ) ct
join country co on ct.countryCode = co.code;