Friday, November 14, 2008

Find N-th highest record in SQL Server

Find N-th highest record in SQL Server
The following list of queries can be used to get N-th maximum record from table in SQL Server.
Here, let we consider a simple employee table. And we need to get the employee details whose salary is the 2nd maximum of the table.

Option: 1

Select top 1 * from employee where salary not in (select max(salary) from employee ) order by salary desc

Option:2

Select top 1 * from (select top 2 * from employee order by salary desc) emp order by emp.salary

Option: 3

Select * from employee e1 where 1 = (select count(distinct(e2.salary)) from employee e2 where e2.salary > e1.salary)

No comments: