2013-05-05 75 views
1

我試圖回答以下問題作爲Mondial DB的一部分。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

嘗試以這種方式(我增加了一個額外加入)

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

在原產地查詢由現場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 
+0

組需要添加您可以編輯您以前的答案。 – 2013-05-06 07:37:48