2

我的数据库类有一个我无法弄清楚的问题。

我有一张名为counties的表,如下所示:

state_code | name | population
           |      |
           |      | 

(每个 state_code 中有多个县)

还有一个叫做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(),这让事情变得非常困难。

谢谢

4

2 回答 2

2
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 或更少。

于 2012-10-27T19:18:55.240 回答
0

这个解决方案非常缓慢和痛苦,但我相信它应该给你你想要的。我很想知道是否有人能想出一个更优雅的解决方案。

 SELECT state.name AS state_name, county.name AS county_name, county.population
 FROM state JOIN county ON state.code = county.state_code
 WHERE  county.name IN (SELECT county.name, COUNT(*) FROM county
          INNER JOIN county AS second_county ON (county.name = second_county.name) AND 
          (county.state_code = second_county.state_code) AND (county.population < state.population) GROUP BY county.name HAVING COUNT(*) <=5)
GROUP BY state.name, county.name, county.population
ORDER BY state.name, county.population DESC
于 2012-10-27T19:17:48.033 回答