如何选择父子关系具有父级最高分的记录

时间:2014-04-30 08:37:20

标签: sql-server sql-server-2008 greatest-n-per-group

我有这样的表:

ExerciseAttempt(attemptId, ExerciseId, Score, studentId)
ExerciseMeta(ExerciseId, ParentId)

每个练习都有一个父母。父母可以有很多孩子练习。现在我想找到这样的记录,即只考虑父母的一个孩子(具有最高分数的孩子)。

例如:

ExericeAttempt:

attemptId | ExerciseId | Score | studentId
1         | 10         |  18   | 10001
2         | 11         |  12   | 10001
3         | 12         |  20   | 10001
4         | 13         |  22   | 10001
5         | 13         |  21   | 10001

ExerciseMeta:

ExerciseId | ParentId
10         |  100
11         |  100
12         |  101
13         |  101

对于这些表格,结果应为

attemptId | ExerciseId | Score | studentId
1         | 10         |  18   | 10001
4         | 13         |  22   | 10001

也可以多次尝试相同的练习。 如何在SQL SERVER中实现这一点?

1 个答案:

答案 0 :(得分:2)

 ;with x as (
    select ea.*, em.parentid,
    row_number() over(partition by parentid order by score desc) as rn
    from ExericeAttempt ea
    inner join ExerciseMeta em
    on ea.ExerciseId = em.ExerciseId
)
select attemptId, ExerciseId, Score, studentId
from x
where rn = 1

结果:

ATTEMPTID   EXERCISEID  SCORE   STUDENTID
1           10          18      10001
4           13          22      10001

结果为Fiddle

相关问题