Friday, February 15, 2013

find nth highest salary in sql server

Finding nth Highest Salary from Emp table  using Row_Number.


Here is the Emp Table.

EMPNOENAMEJOBMGRHIREDATESALCOMMDEPTNO
7369SMITHCLERK790212/17/1980 12:00:00 AM800.00
20
7499ALLENSALESMAN76982/20/1981 12:00:00 AM1600.00300.0030
7521WARDSALESMAN76982/22/1981 12:00:00 AM1250.00500.0030
7566JONESMANAGER78394/2/1981 12:00:00 AM2975.00
20
7654MARTINSALESMAN76989/28/1981 12:00:00 AM1250.001400.0030
7698BLAKEMANAGER78395/1/1981 12:00:00 AM2850.00
30
7782CLARKMANAGER78396/9/1981 12:00:00 AM2450.00
10
7839KINGPRESIDENT
11/17/1981 12:00:00 AM5000.00
10
7844TURNERSALESMAN76989/8/1981 12:00:00 AM1500.000.0030
7900JAMESCLERK769812/3/1981 12:00:00 AM950.00
30
7902FORDANALYST756612/3/1981 12:00:00 AM3000.00
20
7934MILLERCLERK77821/23/1982 12:00:00 AM1300.00
10

Note: ROW_NUMBER works with OVER In Over sort all salary column in descending order so that Highest salary will be in first row.

1.Find Highest Salary from emp table

select * from (
select ROW_NUMBER() over (order by sal desc) rownumber,ename,sal from emp ) o
where o.rownumber=1

O/P:
rownumber    ename    sal
1    KING    5000.00


2.Find Second Highest Salary from Emp Table
O/P:
rownumber    ename    sal
2    FORD    3000.00

3.Find 5th Highest Salary from Emp Table:


select * from (
select ROW_NUMBER() over (order by sal desc) rownumber,ename,sal from emp ) o
where o.rownumber=5

O/P:
rownumber    ename    sal
5    CLARK    2450.00


Like this user can find Nth Highest salary/Number of Employees in the table.


Tags: Find nth highest salary in sql server,Find nth highest salary from sql-server, using Row_number in Sql-Server,using Row_number in SQL Server,using Order by Clause in SQL Server.Sub Queries in SQL Server.

No comments:

Post a Comment