views:

3362

answers:

7

How to find fifth highest salary in a single query in MS Sql Server

+17  A: 

In SQL 2005 & 2008, create a ranked subselect query, then add a where clause where the rank = 5.

select
  *
from
(
  Select
    SalesOrderID, CustomerID, Row_Number() Over (Order By SalesOrderID) as RunningCount
  From
    Sales.SalesOrderHeader
  Where
    SalesOrderID > 10000
  Order By
    SalesOrderID 
) ranked
where 
  RunningCount = 5
Jayden
+4  A: 

These work in MSSQL 2000

DECLARE @result int

SELECT TOP 5 @result = Salary FROM Employees ORDER BY Salary DESC

Syntax should be close. I can't test it at the moment.

Or you could go with a subquery:

SELECT MIN(Salary) FROM (
    SELECT TOP 5 Salary FROM Employees ORDER BY Salary DESC
) AS TopFive

Again, not positive if the syntax is exactly right, but the approach works.

recursive
I want it in a single query using percent... how to get that?select top 5 percent columnnamefrom tablenameorder by descusing this we get first 5 records, but I want only 5th one.
Yogini
Both queries return a single number which is the 5th highest salary.Have you tried them?
recursive
A: 

You can try some thing like :

select salary from Employees a where 5=(select count(distinct salary) from Employees b where a.salary > b.salary) order by salary desc

This approach will work, but has poor performance. It is O(n^2), since for every employee in the outer query, the entire table must be scanned again.
recursive
Also, it will not be correct if there is a tie.
recursive
+1  A: 

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)

you can find any number of highest salary from this query

A: 

you can find by this query

select top 1 salary from (select top 5 salary from tbl_Employee order by salary desc) as tbl

Yagnesh84
A: 

Hi, The below query to gets the Highest salary after particular Employee name.

Just have a look into that!

SELECT TOP 1 salary FROM ( SELECT DISTINCT min(salary) salary FROM emp where salary > (select salary from emp where empname='John Hell') ) a ORDER BY salary

Regards,

Bell

Bell
A: 

select * from employee2 e where 2=(select count(distinct salary) from employee2 where e.salary<=salary)

its working

Nilesh