3

我有一张表可以说排名信息有

username   mvid  votedate
john        1    23-sep-90
john        2    23-sep-90
smith       1    23-sep-90
john        3    24-oct-91
smith       3    24-oct-91
smith       4    25-dec-91
smith       5    25-dec-91

我需要在 sqldeveloper(Oracle) 中编写一个 sql 查询,它会给我每年投票最多的成员。输出应该是用户名,年份,每年的总票数。让我们考虑上面的例子:我需要这样的输出。

username  year  number_Of_Votes
john       1990    2
smith      1991    3

因为在 1990 年,约翰以 1 票的优势击败了史密斯,而在 1991 年,史密斯以 2 票的优势击败了约翰。

我到了计算所有选票的地步,但我无法获得一年中的最大选票数。

这就是我所做的:

select r1.username, 
    Extract(year from r1.votedate)"Year",
    count(username)
from rankinginfo r1
where Extract(year from r1.votedate)  is not null
group by Extract(year from r1.votedate), 
      r1.username;
order by  Extract(year from r1.votedate),
      username;
4

3 回答 3

5
select  *
from    (
        select  VotesPerUserPerYear.*
        ,       dense_rank() over (
                    partition by voteyear
                    order by votecount desc) as rn
        from    (
                select  username
                ,       extract(year from votedate) as voteyear
                ,       count(*) as votecount
                from    YourTable
                group by
                        username
                ,       extract(year from votedate)
                ) VotesPerUserPerYear
        ) SubQueryWithRank
where   rn = 1 -- Only top voter per year

SQL Fiddle 的示例。

于 2013-05-09T11:33:41.817 回答
2

一种方法是

select username, year, cnt from (
select username, cnt, row_number() over (partition by year order by cnt desc) rn
from (
select username, to_char( votedate, 'YYYY' ) year, count(*) cnt
from rankinginfo
group by to_char( votedate, 'YYYY' )
)
) where rn = 1
于 2013-05-09T11:52:01.173 回答
-1

您可以尝试以下一种:

SELECT MAX(point) as HIGHEST

FROM
(SELECT pointA as point FROM tableA

UNION
SELECT pointB as point FROM tableB) t
于 2013-05-09T11:32:53.170 回答