Tuesday, December 18, 2007

How to get the nth highest salary

How to get the nth highest salary
--------------------------------------------------------------------------------

This SQL will find the employee with the nth highest salary from the 'employee' table defined as
emp_id Integer
salary decimal(12,0)

SELECT emp_id, salary
FROM employee a
WHERE ( SELECT COUNT( * )
FROM employee b
WHERE b.salary > a.salary ) = ( n - 1 )

To list all the employees in the 'top - n salary bracket' use:

SELECT emp_id, salary
FROM employee a
WHERE ( SELECT COUNT( * )
FROM employee b
WHERE b.salary > a.salary ) <= ( n - 1 )

No comments: