How to find third or nᵗʰ maximum salary from salary table?

后端 未结 30 564
醉酒成梦
醉酒成梦 2020-11-30 16:30

How to find third or nth maximum salary from salary table(EmpID, EmpName, EmpSalary) in optimized way?

相关标签:
30条回答
  • 2020-11-30 17:26

    In 2008 we can use ROW_NUMBER() OVER (ORDER BY EmpSalary DESC) to get a rank without ties that we can use.

    For example we can get the 8th highest this way, or change @N to something else or use it as a parameter in a function if you like.

    DECLARE @N INT = 8;
    WITH rankedSalaries AS
    (
    SELECT
    EmpID
    ,EmpName
    ,EmpSalary,
    ,RN = ROW_NUMBER() OVER (ORDER BY EmpSalary DESC)
    FROM salary
    )
    SELECT
    EmpID
    ,EmpName
    ,EmpSalary
    FROM rankedSalaries
    WHERE RN = @N;
    

    In SQL Server 2012 as you might know this is performed more intuitively using LAG().

    0 讨论(0)
  • 2020-11-30 17:26

    Just change the inner query value: E.g Select Top (2)* from Student_Info order by ClassID desc

    Use for both problem:

    Select Top (1)* from 
    (
     Select Top (1)* from Student_Info order by ClassID desc 
    ) as wsdwe
    order by ClassID 
    
    0 讨论(0)
  • 2020-11-30 17:27

    Third or nth maximum salary from salary table without using subquery

    select salary from salary
       ORDER   BY salary DESC
       OFFSET  N-1 ROWS
       FETCH NEXT 1 ROWS ONLY
    

    For 3rd highest salary put 2 in place of N-1

    0 讨论(0)
  • 2020-11-30 17:27
    SELECT MIN(COLUMN_NAME)
    FROM   (
               SELECT DISTINCT TOP 3     COLUMN_NAME
               FROM   TABLE_NAME
               ORDER BY
                      COLUMN_NAME        DESC
           ) AS 'COLUMN_NAME'
    
    0 讨论(0)
  • 2020-11-30 17:29

    Optimized way: Instead of subquery just use limit.

    select distinct salary from employee order by salary desc limit nth, 1;
    

    See limit syntax here http://www.mysqltutorial.org/mysql-limit.aspx

    0 讨论(0)
  • 2020-11-30 17:30

    Use ROW_NUMBER(if you want a single) or DENSE_RANK(for all related rows):

    WITH CTE AS
    (
        SELECT EmpID, EmpName, EmpSalary,
               RN = ROW_NUMBER() OVER (ORDER BY EmpSalary DESC)
        FROM dbo.Salary
    )
    SELECT EmpID, EmpName, EmpSalary
    FROM CTE
    WHERE RN = @NthRow
    
    0 讨论(0)
提交回复
热议问题