Home > Software design >  How to Select Top 3 Highest Values From Each GROUP
How to Select Top 3 Highest Values From Each GROUP

Time:12-26

I have a Marks table where Student's Quiz Marks and Assignment marks are entered in the following way

StudentID CourseID Quiz1 Quiz2 Quiz3 Quiz4 Quiz5 Assignment1 Assignment2 Assignment3 Assignment4 Assignment5
1 321 10 8 4 1 9 7 3 9 8 5
2 321 6 10 6 3 8 4 7 1 8 6
3 321 7 9 2 8 4 10 7 5 8 3
4 321 7 2 6 4 8 3 6 9 10 5
5 321 3 4 5 7 10 5 7 8 3 9

Now I want to select the highest 3 quiz numbers and the highest 3 assignment numbers and sum them as the total quiz and total assignment numbers respectively for each student. I have bold highest numbers in the above table for a better understanding

The result should be something like this

StudentID CourseID QuizTotal AssignmentTotal
1 321 27 24
2 321 24 21
3 321 24 25
4 321 21 25
5 321 22 24

What I have Tried is unpivot technique but the result is not what I am expecting. Here's what I tried

SELECT TOP(3) StudentID,  Marks 
FROM
(SELECT StudentID,CourseID , Quiz1, Quiz2, Quiz3, Quiz4, Quiz5  FROM Marks) stu

UNPIVOT

(Marks FOR QuizNo IN (Quiz1, Quiz, Quiz3, Quiz4, Quiz5)) AS mrks 


WHERE    (CourseID = 321)
Order by Marks Desc



CodePudding user response:

One way is to unpivot and sum marks with CROSS APPLY

SELECT StudentID, CourseID, qm.m, am.m
FROM Marks 
cross apply (
  select sum (q) m
  from (
     select top(3) q
     from (
       values
         (Quiz1),(Quiz2),(Quiz3),(Quiz4),(Quiz5)
       ) t(q)
     order by q desc
     ) tq
  ) qm
cross apply (
  select sum (q) m
  from (
     select top(3) q
     from (
       values
         (Assignment1),(Assignment2),(Assignment3),(Assignment4),(Assignment5)
       ) t(q)
     order by q desc
     ) tq
  ) am
  • Related