Oct 27, 2015

Posted in , , , ,

MS SQL 2008: How to Find the Nth Maximum and Minimum Value in a Column?

This post will explain about how to find the Nth Maximum and Minimum Value in a Column. There are several methods to find out the Nth maximum/minimum value using SQL. This article discusses on such method to find Nth maximum value from a desired table.

MS SQL 2008: How to Find the Nth Maximum and Minimum Value in a Column?

Now write the following code:
DECLARE @n INT
SET @n=2
SELECT USER_ID,username from
(
 SELECT USER_ID,username,ROW_NUMBER() OVER(ORDER BY USER_ID DESC) AS Higher
 FROM User_Details
) AS Higher
 WHERE Higher=@n

DECLARE @nth INT
SET @nth=2
SELECT USER_ID,username from
(
 SELECT USER_ID,username,ROW_NUMBER() OVER(ORDER BY USER_ID ASC) AS Lower
 FROM User_Details
) AS Lower
 WHERE Lower=@nth

Enter the value at @n what you have to enter then i will display according to @n value. I hope it works for you!

0 comments:

Post a Comment

thanks for your comment!