Monday, 12 March 2012

FIND Nth Maximum value and Nth minimum Value from a colum in a table in MS-Sql Server.

 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

No comments:

Post a Comment