In this query, I will show you how to fetch the highest value in a Group or Category. We will be creating a sample table called Student - StudentId, SubjectId and Marks. We have to find out that in each Subject(group), which Student scored the highest marks.
Sample Data
DECLARE @Student TABLE
(
StudentId int, SubjectId int, Marks float
)
INSERT @Student
SELECT 1,1,8.0 UNION ALL
SELECT 2,1,5.0 UNION ALL
SELECT 3,1,7.0 UNION ALL
SELECT 4,1,9.5 UNION ALL
SELECT 1,2,9.0 UNION ALL
SELECT 2,2,7.0 UNION ALL
SELECT 3,2,4.0 UNION ALL
SELECT 4,2,7.5
Query to fetch Student with highest marks in each Subject
SELECT SubjectId,StudentId,Marks
FROM
(SELECT ROW_NUMBER() OVER(PARTITION BY SubjectId Order by Marks desc) as Topp,* from @Student) Stu
WHERE Stu.Topp =1
Results
SubjectId StudentId Marks
1 4 9.5
2 1 9
2 comments:
Excellent! But how to find Highest and Second Highest value?
I also want to do it using Common Table Expression?
Post a Comment