我的数据库类有一个我无法解决的问题。
我有一个名为counties的表,如下所示:
state_code | name | population
| |
| |
(每个州代码内有多个县)
还有另一个名为states的表,它只是
state_code | name
|
|
无论如何,我需要一个返回方案(state_name、county_name、county_population)的查询,该方案按州名称的顺序列出每个州人口最多的五个县名称(按人口降序排列)以及这些县的人口.
我有一个查询可以生成正确的方案,但它显示的结果太多,而不仅仅是前 5 个:
SELECT state.name AS state_name, county.name AS county_name, county.population
FROM state JOIN county ON state.code = county.state_code
GROUP BY state.name, county.name, county.population
ORDER BY state.name, county.population DESC
我尝试过涉及排名的更复杂的解决方案,但是我们学校只有 PostgreSQL 8.3 版本,它没有 PARTITION OVER 或 RANK(),这使得事情变得非常困难。
谢谢
最佳答案
select state_name, county_name, population
from (
select
s.name state_name,
c.name county_name,
c.population,
row_number() over(partition by s.state_code order by population desc) rn
from
states s
inner join
counties c on s.state_code = c.state_code
) s
where rn <= 5
order by state_name, population desc
row_number 窗口函数对每个状态内的行进行编号。在外部查询中,我将行数限制为 5 或更少。
关于sql - PostgreSQL 每个州人口最多的 5 个县,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13103096/