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

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

    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

提交回复
热议问题