2015-11-17 46 views
1

我正在使用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; 

这给了我每个国家的城市,其人口,而不仅仅是大城市的ALL

+0

您应该提供表格create和insert语句作为示例数据。至少在SQL Fiddle中构建简单模式并将其链接到问题。我们没有你的“城市”和“国家”表。此外,你应该显示所需的输出,而不是用文字解释。除非与它相关,否则不要添加[tag:sqlplus]。你的问题与Oracle SQL有关,而SQL * Plus是一个客户端工具。请参阅[**如何提出问题**](http://tkyte.blogspot.de/2005/06/how-to-ask-questions.html) –

+1

[必须出现在GROUP BY子句中或在一个聚合函数中使用](http://stackoverflow.com/questions/19601948/must-appear-in-the-group-by-clause-or-be-used-in-an-aggregate-function) – Sebas

回答

2

使用分析功能。像这样的东西应该工作(未经测试):

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

不能使用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; 
+0

什么如果两个城市有相同的人口?你会加倍你的结果集。 – Lock

+0

你不想那样? – Cr1xus

+0

只需在country.name – Cr1xus

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 

功能类似于甲骨文ROW_NUMBER帮助。
希望这个帮助。

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