Mondial DB内部查询

时间:2013-05-05 10:35:33

标签: sql

我正在尝试回答以下问题,作为Mondial DB的一部分。

-- For each country display the city with the highest population together with the number of the population.

表格是:

国家/地区(代码,姓名,资本,省份,地区,人口)

城市(名称,国家,省,经度,纬度,人口)

到目前为止,我有以下内容:

SELECT 
    Country.Name, MaxCity.CityName, MaxCity.Population
FROM
    (SELECT 
        MAX(Population) AS Population,
            City.Country,
            City.Name AS CityName
    FROM
        City
    GROUP BY City.Country) AS MaxCity
        JOIN
    Country ON Country.Code = MaxCity.Country;

哪里出错了?

2 个答案:

答案 0 :(得分:2)

以这种方式尝试(我添加了额外的连接)

SELECT 
    Country.Name, City.CityName, City.Population
FROM
    Country Join City On Country.Code = City.Country
Join (SELECT 
        MAX(Population) AS Population,Country as Country from City Group By Country)  as X
On City.Country = x.Country and City.Population = x.Population

答案 1 :(得分:1)

在原始查询中,需要按字段city.name

添加分组
    select country.name, maxcity.cityname, maxcity.population
    from
        (select 
            MAX(population) as population,
        city.country,
        city.name as cityname
    from city
    group by city.country, city.name) as maxcity
            join
    country on country.code = maxcity.country