Wednesday, May 22, 2013

Query to Find second highest/Nth highest salary in SQL Server and Oracle

SQL Sever
========
select top 1 a.* from (
select top 4 salary from table1 order by salary DESC ) a order by a.salary ASC;

Now in generic terms... Lets say for Nth salary.

select top 1 a.* from (
select top N salary from table1 order by salary DESC ) a order by a.salary ASC;

Just replace N with the number you want to find the salary. (N = 1 for first, N =2 for second, N= 3 for third.. so on..).

Oracle
======
select * from (
select tb1.*, rownum Rnum from (
select * from table1 order by salary DESC) tb1 where rownum <= 2) where Rnum >= 2;

Now to make it generic.. Lets say for Nth salary.

select * from (
select tb1.*, rownum Rnum from (
select * from table1 order by salary DESC) tb1 where rownum <= N) where Rnum >= N;

Just replace N with the number you want to find the salary. (N = 1 for first, N =2 for second, N= 3 for third.. so on..).

No comments:

Post a Comment