Reputation: 25153
I have tables in like this:
ExerciseAttempt(attemptId, ExerciseId, Score, studentId)
ExerciseMeta(ExerciseId, ParentId)
Each exercise has one parent. A parent can have many child exercises. Now I want to find the records such that only one child of a parent(the one with max score) is considered.
For example:
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
For these tables the result should be
attemptId | ExerciseId | Score | studentId
1 | 10 | 18 | 10001
4 | 13 | 22 | 10001
Also multiple attempts of a same exercise are possible. How can I achieve this in SQL SERVER?
Upvotes: 0
Views: 169
Reputation: 10098
;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
Result:
ATTEMPTID EXERCISEID SCORE STUDENTID
1 10 18 10001
4 13 22 10001
Result in Fiddle.
Upvotes: 2