Select the Highest value in a Group/Category using SQL Server 2005/2008

In one of my previous posts, I had explained how to SELECT TOP N Rows Per Group/Category

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



About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

2 comments:

Anonymous said...

Excellent! But how to find Highest and Second Highest value?

Anonymous said...

I also want to do it using Common Table Expression?