SQL查找每个组的最高记录

时间:2012-03-08 08:57:40

标签: sql-server

有点卡在查询上。我有一个测验结果表,其中包含:

ID of the player,  
QuizID, 
Number of seconds it took to complete the quiz, 
Number of correct answers

我如何找到每个测验的获胜者。 =具有最大正确答案数的玩家和每个QuizID的最小秒数

我尝试了很多方法,但我无法得到正确的结果。希望有人可以提供帮助。

谢谢!

2 个答案:

答案 0 :(得分:4)

CTE将为测验中的每位玩家计算位置。主查询仅过滤第一个位置。

; with quiz as (
   select QuizId, PlayerID, row_number() over (partition by QuizId order by count_answers desc, seconds) rownum
      from QuizResults
)
select *
from QuizResults
   inner join Quiz
      on QuizResults.QuizID = Quiz.QuizID
      and QuizResults.PlayerID = Quiz.PlayerID
where rownum = 1

答案 1 :(得分:0)

未验证:

select ID 
from your_table 
group by QuizId
having max(count_answers) and min(seconds)