The query to find the Nth Maximum and Minimum values in an SQL Server table column, using the Row_Number() function. We will find the 3rd highest and the 3rd lowest values in the column.
DECLARE @tmp TABLE(id integer, amount integer)
INSERT INTO @tmp values(4, 9543)
INSERT INTO @tmp values(6, 34)
INSERT INTO @tmp values(3, 54)
INSERT INTO @tmp values(2, 6632)
INSERT INTO @tmp values(5, 645)
INSERT INTO @tmp values(1, 1115)
INSERT INTO @tmp values(7, 345)
-- FIND Nth Maximum value
SELECT id, amount
FROM
(
SELECT id, amount, Row_Number() OVER(ORDER BY amount DESC) AS highest
FROM @tmp
) as x
WHERE highest = 3
-- FIND Nth Minimum value
SELECT id, amount
FROM
(
SELECT id, amount, Row_Number() OVER(ORDER BY amount ASC) AS lowest
FROM @tmp
) as x
WHERE lowest = 3
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.

Sugu NeshPosted May 20, 2014, 9:21 AM
Please post me how to find using rank??
Sompal AryaPosted Feb 27, 2014, 4:43 AM
nice work..
Sompal AryaPosted Feb 24, 2014, 2:17 AM
Thanx for sharing...