April 01, 2009

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



Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

2 Responses to "Select the Highest value in a Group/Category using SQL Server 2005/2008"
  1. Anonymous said...
    April 4, 2009 at 3:19 AM

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

  2. Anonymous said...
    April 4, 2009 at 3:34 AM

    I also want to do it using Common Table Expression?

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions