SQL query to find Nth highest salary from a salary table

前端 未结 11 2246
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 10:45

How can I find the Nth highest salary in a table containing salaries in SQL Server?

11条回答
  •  心在旅途
    2020-11-28 11:17

    Solution 1: This SQL to find the Nth highest salary should work in SQL Server, MySQL, DB2, Oracle, Teradata, and almost any other RDBMS: (note: low performance because of subquery)

    SELECT * /*This is the outer query part */
    FROM Employee Emp1
    WHERE (N-1) = ( /* Subquery starts here */
    SELECT COUNT(DISTINCT(Emp2.Salary))
    FROM Employee Emp2
    WHERE Emp2.Salary > Emp1.Salary)
    

    The most important thing to understand in the query above is that the subquery is evaluated each and every time a row is processed by the outer query. In other words, the inner query can not be processed independently of the outer query since the inner query uses the Emp1 value as well.

    In order to find the Nth highest salary, we just find the salary that has exactly N-1 salaries greater than itself.


    Solution 2: Find the nth highest salary using the TOP keyword in SQL Server

    SELECT TOP 1 Salary
    FROM (
          SELECT DISTINCT TOP N Salary
          FROM Employee
          ORDER BY Salary DESC
          ) AS Emp
    ORDER BY Salary
    

    Solution 3: Find the nth highest salary in SQL Server without using TOP

    SELECT Salary FROM Employee 
    ORDER BY Salary DESC OFFSET N-1 ROW(S) 
    FETCH FIRST ROW ONLY
    

    Note that I haven’t personally tested the SQL above, and I believe that it will only work in SQL Server 2012 and up.

提交回复
热议问题