对于每个国家,找到人口最多的城市和城市人口

时间:2015-11-17 05:16:28

标签: sql database oracle

我正在使用Mondial数据库架构并试图找到:对于每个国家/地区,找到人口最多且城市人口最多的城市。

现在我有:

SELECT Country.Name, city.name, MAX(city.population) Population
FROM city
Join Country
On Country.Code=City.Country
WHERE city.population IS NOT NULL
GROUP BY Country.Name, city.name
ORDER BY Country.Name;

这给了我所有的每个国家的城市及其人口,而不仅仅是最大的城市。

4 个答案:

答案 0 :(得分:3)

使用分析功能。这样的事情应该有效(未经测试):

select
  country.name,
  city.name,
  city.population
from
  country
join
(
  select
    country,
    name,
    population,
    row_number() over ( partition by population desc) as rn
  from
    city
) city on
  city.country = country.code
  and city.rn = 1
order by
  country.name

答案 1 :(得分:2)

在oracle中不知道,但如果在SQL Server中完成,可以这样做:

    Select * from
        (select 
        Country.Name,
        city.name,
        city.population,
        ROW_NUMBER() over(partition by Country.Name order by Country.Name,city.population desc) RowNum
    from Country inner join city city on Country.Code=City.Country) tbl
    where RowNum = 1

在oracle中类似于row_number的功能会有所帮助 希望这有帮助。

答案 2 :(得分:0)

这似乎有效。

根据包含聚合函数的列过滤查询结果也很有用。

SELECT ct.name AS "Country", c1.name AS "City", c1.population AS "Population"
FROM   city c1
    JOIN country ct
    ON c1.country = ct.code
WHERE  c1.population = (SELECT max(population)
                        FROM   city c2
                        WHERE  c1.country = c2.country)
ORDER BY country

答案 3 :(得分:-1)

您不能在多个选择中使用MAX 试试这个:

SELECT Country.Name, city.name, city.population
FROM city
Join Country
On Country.Code=City.Country
WHERE city.population IS NOT NULL and city.population in (SELECT MAX(population) FROM city limit 1)
GROUP BY Country.Name, city.name
ORDER BY Country.Name;