How to find the employee with the second highest salary?

前端 未结 5 1984
生来不讨喜
生来不讨喜 2020-12-02 01:10

Is there any predefined function or method available to get the second highest salary from an employee table?

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 01:31

    It's easier handling Top-N queries with Oracle DB 12c which introduced such a syntax :

    [ OFFSET offset { ROW | ROWS } ]
    [ FETCH { FIRST | NEXT } [ { rowcount | percent PERCENT } ]
        { ROW | ROWS } { ONLY | WITH TIES } ]
    

    to be used in a query after ORDER BY list.

    In this case consider using :

    select *
      from emp
     order by sal desc
    offset 1 rows fetch next 1 rows only
    

    where using offset is optional, as already seen from the syntax, and points out the starting point for the fetch clause will be offset + 1.

    A special case is having ties which means multiple rows match the value of the Nth row(here we need 2nd row). If there are more than one people with the same salary for the top-second position, then we need to replace only keyword by with ties to return them all :

    select *
      from emp
     order by sal desc
    offset 1 rows fetch next 1 rows with ties
    

    Demo

提交回复
热议问题