Tuesday, September 01, 2009

SQLServer Find nth lowest salary from Employee

SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP 8 salary
FROM tblemployee
ORDER BY salary) a
ORDER BY salary DESC


You can change and use it for getting nth highest salary from Employee table as follows

SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP n salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

Query to Find the Second/Nth Highest Column Value in a Table

SELECT TOP 1 Salary FROM (SELECT TOP 2 Salary FROM Employee ORDER BY Salary DESC) AS E ORDER BY Salary ASC

Note that if we had to get the fourth highest Salary, we could do so by simply changing the subquery from TOP 2 to TOP 4

Query to Find the Second Lowest Column Value in a Table
SELECT TOP 1 Salary FROM (SELECT TOP 2 Salary FROM Employee ORDER BY Salary ASC) AS E ORDER BY Salary DESC

No comments: