How to get second-highest salary employees in a table

后端 未结 30 1036
离开以前
离开以前 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 21:00

    How about a CTE?

    ;WITH Salaries AS
    (
        SELECT Name, Salary,
           DENSE_RANK() OVER(ORDER BY Salary DESC) AS 'SalaryRank'
        FROM 
            dbo.Employees
    )
    SELECT Name, Salary
    FROM Salaries  
    WHERE SalaryRank = 2
    

    DENSE_RANK() will give you all the employees who have the second highest salary - no matter how many employees have the (identical) highest salary.

提交回复
热议问题