在列中具有相同值的表中找到第一和第二最高值之间的差异

时间:2018-10-13 20:04:18

标签: sql postgresql

我有一个名为候选人的表,用于存储美国总统选举中的候选人数据。

该表的列为:

  • 名称(varchar)
  • election_year(int)
  • 投票(int)
  • winner(boolean)

我需要弄清所有选举年中投票最多的候选人与投票第二的候选人之间的差异。我尝试用Google的薪水来获得第二高的薪水,但是假设要在整个表中拿到第二高的薪水,而我只想从选举年中拿到第二高的薪水,但是我不知道该怎么做。

我可以对如何完成此操作有任何见解吗?

离我最近的是

select max(votes) - min(votes)
from candidates
group by election_year;

但是那不是我想要的。

2 个答案:

答案 0 :(得分:2)

在派生表中使用窗口函数rank()

select election_year, max(votes)- min(votes) as difference
from (
    select election_year, votes, rank() over w
    from candidates
    window w as (partition by election_year order by votes desc)
    ) s
where rank < 3
group by election_year

阅读文档:

答案 1 :(得分:0)

因此,我找到了一种不使用窗口函数的方法,其过程如下:

select max(votes - second_place_votes)
from election inner join (
    select election_year, max(votes) as second_place_votes
    from election
    where winner_loser_indic='L'
    group by election_year
    order by election_year
) as second_max_votes on election.election_year=second_max_votes.election_year
where winner_loser_indic='W';
相关问题