SQL query to find Nth highest salary

前端 未结 9 811
清酒与你
清酒与你 2020-12-15 01:52

I am referring to following query to find Nth highest salary of a employee.

select sal from emp t where &n = (select count(sal) from (select distinct sal         


        
9条回答
  •  死守一世寂寞
    2020-12-15 02:41

    Query:

    select 
        ename  
        ,sal  
        ,dense_rank() over (order by sal desc) ranking  
    from   emp;  
    

    output:

    ENAME   SAL   RANKING
    KING    5000    1   
    FORD    3000    2  
    SCOTT   3000    2  
    JONES   2975    3  
    CLARK   2850    4  
    BLAKE   2850    4  
    ALLEN   1600    5  
    

    Wrap a filter around and pick out the Nth highest salary, say the 4th highest salary.

    Query:

    select *  
    from  
    (  
      select ename  
            ,sal  
            ,dense_rank() over (order by sal desc) ranking  
      from   emp  
    )  
    where ranking = 4 -- Replace 4 with any value of N  
    

    output:

    ENAME  SAL  RANKING
    BLAKE  2850     4  
    CLARK  2850     4  
    

提交回复
热议问题