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

后端 未结 30 563
醉酒成梦
醉酒成梦 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:23

    Try this

    SELECT TOP 1 salary FROM (
       SELECT TOP 3 salary 
       FROM employees 
       ORDER BY salary DESC) AS emp 
    ORDER BY salary ASC
    

    For 3 you can replace any value...

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

    To get third highest value from table

    SELECT * FROM tableName ORDER BY columnName DESC LIMIT 2, 1
    
    0 讨论(0)
  • 2020-11-30 17:23

    --nth highest salary

    select * 
    from (select lstName, salary, row_number() over( order by salary desc) as rn 
          from employee) tmp
    where rn = 2
    

    --(nth -1) highest salary

    select * 
    from employee e1
    where 1 = (select count(distinct salary)  
               from employee e2
               where e2.Salary > e1.Salary )
    
    0 讨论(0)
  • 2020-11-30 17:25
    declare @maxNthSal as nvarchar(20)
    SELECT TOP 3 @maxNthSal=GRN_NAME FROM GRN_HDR   ORDER BY GRN_NAME DESC
    print @maxNthSal
    
    0 讨论(0)
  • 2020-11-30 17:25

    By subquery:

    SELECT salary from
    (SELECT rownum ID, EmpSalary salary from
    (SELECT DISTINCT EmpSalary from salary_table order by EmpSalary DESC)
    where ID = nth)
    
    0 讨论(0)
  • 2020-11-30 17:26

    Replace N with your Max Number

    SELECT *
    FROM Employee Emp1
    WHERE (N-1) = (
    SELECT COUNT(DISTINCT(Emp2.Salary))
    FROM Employee Emp2
    WHERE Emp2.Salary > Emp1.Salary)
    

    Explanation

    The query above can be quite confusing if you have not seen anything like it before – the inner query is what’s called a correlated sub-query because the inner query (the subquery) uses a value from the outer query (in this case the Emp1 table) in it’s WHERE clause.

    And Source

    0 讨论(0)
提交回复
热议问题