How to get second-highest salary employees in a table

后端 未结 30 1032
离开以前
离开以前 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 20:53

    I think you would want to use DENSE_RANK as you don't know how many employees have the same salary and you did say you wanted nameS of employees.

    CREATE TABLE #Test
    (
        Id INT,
        Name NVARCHAR(12),
        Salary MONEY
    )
    
    SELECT x.Name, x.Salary
    FROM
            (
            SELECT  Name, Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) as Rnk
            FROM    #Test
            ) x
    WHERE x.Rnk = 2
    

    ROW_NUMBER would give you unique numbering even if the salaries tied, and plain RANK would not give you a '2' as a rank if you had multiple people tying for highest salary. I've corrected this as DENSE_RANK does the best job for this.

提交回复
热议问题