How can I select the record with the 2nd highest salary in database Oracle?

后端 未结 18 1414
孤城傲影
孤城傲影 2020-12-30 17:27

Suppose I have a table employee with id, user_name, salary. How can I select the record with the 2nd highest salary in Oracle?

I googled it, find this solution, is t

18条回答
  •  我在风中等你
    2020-12-30 17:56

    I would suggest following two ways to implement this in Oracle.

    1. Using Sub-query:
    select distinct SALARY   
    from EMPLOYEE e1  
    where 1=(select count(DISTINCT e2.SALARY) from EMPLOYEE e2 where         
      e2.SALARY>e1.SALARY);
    

    This is very simple query to get required output. However, this query is quite slow as each salary in inner query is compared with all distinct salaries.

    1. Using DENSE_RANK():
    select distinct SALARY   
    from
      (
        select e1.*, DENSE_RANK () OVER (order by SALARY desc) as RN 
        from EMPLOYEE e
      ) E
     where E.RN=2;
    

    This is very efficient query. It works well with DENSE_RANK() which assigns consecutive ranks unlike RANK() which assigns next rank depending on row number which is like olympic medaling.

    Difference between RANK() and DENSE_RANK(): https://oracle-base.com/articles/misc/rank-dense-rank-first-last-analytic-functions

提交回复
热议问题