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 DataDECLARE @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
ResultsSubjectId 1st Rank 2nd Rank
1 9.5 8
2 9 7.5
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
No comments:
Post a Comment