Wednesday 22 February 2012

Find the nth highest salary in sql -Query to retrieve value

The following solution is for getting 6th highest salary from Employee table :-
 SELECT TOP 1 salaries
FROM (
SELECT DISTINCT TOP 6 salaries
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 salaries
FROM (
SELECT DISTINCT TOP n salaries
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

where n > 1 (n is always greater than one)
Same example converted in SQL Server 2005 to work with Database AdventureWorks.
USE AdventureWorks;
GO
SELECT TOP 1 Rates
FROM (
SELECT DISTINCT TOP 4 Rate
FROM HumanResources.EmployeePayHistories
ORDER BY Rate DESC) A
ORDER BY Rate
GO

No comments:

Post a Comment