Monday, May 9, 2011

Query to find nth max value of a column

Consider the following Employee table with a single column for salary.
                          +------+
                          | Sal  |
                          +------+
                          | 3500 | 
                          | 2500 | 
                          | 2500 | 
                          | 5500 |
                          | 7500 |
                          +------+
The following query will return the Nth Maximum element.
select SAL from EMPLOYEE E1 where 
 (N - 1) = (select count(distinct(SAL)) 
            from EMPLOYEE E2 
            where E2.SAL > E1.SAL )
For eg. when the second maximum value is required,
  select SAL from EMPLOYEE E1 where 
     (2 - 1) = (select count(distinct(SAL)) 
                from EMPLOYEE E2 
                where E2.SAL > E1.SAL )
 
                    +------+
                    | Sal  |
                    +------+
                    | 5500 |
                    +------+
 
The following query will return the Nth Minimum element.
select SAL from EMPLOYEE E1 where
 
(N - 1) = (select count(distinct(SAL))
           
from EMPLOYEE E2
           
where E2.SAL < E1.SAL )
For eg. when the second Minimum value is required,
  select SAL from EMPLOYEE E1 where
     
(2 - 1) = (select count(distinct(SAL))
               
from EMPLOYEE E2
               
where E2.SAL < E1.SAL )

 
                    +------+
                    | Sal  |
                    +------+
                    | 3500 |
                    +------+
 
 
Second Way:---


DECLARE @SalaryPosition INT
SET @SalaryPosition = 2
SELECT *
FROM Employee E1
WHERE @SalaryPosition =  
          (
            SELECT COUNT(DISTINCT E2.Salary) 
            FROM Employee E2
            WHERE E2.Salary >= E1.Salary
          ) 
 
 
SELECT TOP 1 salary

FROM (

SELECT DISTINCT TOP 6 salary

FROM employee

ORDER BY salary DESC) a

ORDER BY salary

You can change and use it for getting  nth highest salary from Employee table as follows

SELECT TOP 1 salary

FROM (

SELECT DISTINCT TOP n salary

FROM employee

ORDER BY salary DESC) a

ORDER BY salary

where n > 1 (n  is always greater than one) 

No comments: