April 04, 2010

Find the Nth Maximum and Minimum Value in a Column




Here’s a simple query to find the Nth Maximum and Minimum values in a SQL Server table column using the Row_Number() function. We will find the 3rd highest and 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

OUTPUT
Nth Maximum Minimum

The first output shows the 3rd maximum value in the column whereas the second output shows the 3rd minimum value in the column


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

3 Responses to "Find the Nth Maximum and Minimum Value in a Column"
  1. Madhivanan said...
    April 9, 2010 at 3:55 AM

    Other possible methods
    http://beyondrelational.com/blogs/madhivanan/archive/2007/08/27/find-nth-maximum-value.aspx

  2. Anonymous said...
    August 17, 2011 at 8:03 AM

    Works but not as advertised, this returns the 2nd highest and lowest

  3. Anonymous said...
    August 17, 2011 at 8:06 AM

    Actualy it does work as advertised, but the results shown do not match the code. The results show the second highest/lowest entries, code is for the third.

 

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