How to get second-highest salary employees in a table

后端 未结 30 1035
离开以前
离开以前 2020-12-23 20:15

It\'s a question I got this afternoon:

There a table contains ID, Name, and Salary of Employees, get names of the second-highest salary employees, in SQL Server

30条回答
  •  滥情空心
    2020-12-23 21:13

    There are two way to do this first:

    Use subquery to find the 2nd highest

    SELECT MAX(salary) FROM employees
    WHERE salary NOT IN (
    SELECT MAX (salary) FROM employees)
    

    But this solution is not much good as if you need to find out the 10 or 100th highest then you may be in trouble. So instead go for window function like

    select * from
    (
    select salary,ROW_NUMBER() over( 
    order by Salary desc) as
    rownum from    employees
    ) as t where t.rownum=2
    

    By using this method you can find out nth highest salary without any trouble.

提交回复
热议问题