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

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

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

30条回答
  •  猫巷女王i
    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().

提交回复
热议问题