April 05, 2009

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




In one of my previous posts Select the Highest value in a Group/Category using SQL Server 2005/2008, a user asked me if it was possible to find the Highest and the Second Highest Value in a Group/Category. He also wanted to use a Common Table Expression to do so.

Here's the modified query to find the Maximum and Second Maximum value in a Group/Category using a CTE in SQL Server 2005/2008

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 the highest and second highest marks in each Subject


;With CTE


AS


(Select Row_number() Over(Partition By SubjectId Order By Marks Desc) as Topp,* From @Student)


Select SubjectId,


  Max(Case When Topp=1 Then Marks End) as '1st Rank',


  Max(Case When Topp=2 Then Marks End) as '2nd Rank'


From CTE


Group By SubjectId




Results


SubjectId    1st Rank    2nd Rank


1              9.5          8


2              9            7.5



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

0 Responses to "Select the Highest and Second Highest value in a Group/Category using SQL Server 2005/2008"
 

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