Oracle SQL查询 - 仅显示最大值?

时间:2013-06-03 13:44:34

标签: sql group-by

我在oracle SQL查询中有以下代码。此代码查找成员的用户名以及他们每年投票的次数。如何修改它以便它只显示投票次数最多的用户?

SELECT username, count(username), extract(year from voteDate) as vote_year,
max(count(*)) over (partition by extract(year from voteDate)) as Max_votes
FROM rankingInfo NATURAL JOIN memberinfo
GROUP BY username, extract(year from voteDate);

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的查询,您的max_votes会返回您想要的最多投票数,而count(username)会返回每个用户的投票数。如果是这样,您可以将结果放在子查询中,然后只需添加WHERE条件:

SELECT * 
FROM (
   SELECT username, count(username) votes, extract(year from voteDate) as vote_year,
       max(count(*)) over (partition by extract(year from voteDate)) as Max_votes
   FROM rankingInfo NATURAL JOIN memberinfo
   GROUP BY username, extract(year from voteDate)
) T
WHERE votes = max_votes