Thursday, July 30, 2015

How to find nth highest salary using rank and row_number?

2nd ..3rd highest salary using Aggregate Function MAX-

MAX returns maximum value of expr. You can use it as an aggregate or analytic function.

2nd highest salary-

select MAX(sal) from EMP 
WHERE 
sal <> ( select max(sal) from emp );    -- single value in a WHERE clause

3rd highest salary-

select MAX(sal) from EMP 
WHERE 
sal NOT IN            -- multiple values in a WHERE clause

         (select max(sal) from emp)   -- till here >> return 2nd highest
       , (select max(sal) from emp where sal <> (select max(sal) from emp)) -- till here >> return 3rd highest
);

4th highest salary-

select MAX(sal) from EMP 
WHERE 
sal NOT IN         -- multiple values in a WHERE clause

         ( select max(sal) from emp )   -- till here >> return 2nd highest
       , ( select max(sal) from emp where sal <> (select max(sal) from emp) ) -- till here >> return 3rd highest
       , ( select MAX(sal) from EMP WHERE sal NOT IN ( (select max(sal) from emp) , (select max(sal) from emp where sal <> (select max(sal) from emp))) )
);

Using this logic, you can find nth highest salary.
Note: The answer above is actually not optimal from a performance standpoint since it uses a subquery.


Find the nth highest salary in Oracle using ROWNUM (Best)

select * from
 (
    select EMPNO, Sal
    , row_number() over (order by Sal DESC) ROW_NUMBER
    from Emp
)
where ROW_NUMBER = n;  /*n is nth highest salary*/


Find the nth highest salary in Oracle using RANK

select * FROM 
(
    select EMPNO, Sal
    ,rank() over (order by Sal DESC) ranking
    from Emp
)
WHERE ranking = n;  /*n is nth highest salary*/

No comments:

Post a Comment