How to get nᵗʰ highest value using plain SQL

前端 未结 8 1079
孤城傲影
孤城傲影 2021-01-24 23:42

What is the simplest way to get the nth highest value from a result set using plain SQL?

The result set would be huge, thus need to consider performance too.

8条回答
  •  说谎
    说谎 (楼主)
    2021-01-25 00:20

    Let's say you want to find the 5th highest salary, you first take the first 5 distinct salary order by descending order so that the last one is the 5th highest salary (See inner query). You then reorder it in ascending order and take the first.

    SELECT TOP 1 Salary FROM
    (
      SELECT DISTINCT TOP 5 Salary
      FROM Employee
      ORDER BY Salary DESC)  t
    
    ORDER BY  Salary ASC
    

提交回复
热议问题