Nth max salary in Oracle

前端 未结 26 1573
名媛妹妹
名媛妹妹 2020-11-30 07:02

To find out the Nth max sal in oracle i\'m using below query

SELECT DISTINCE sal 
FROM emp a 
WHERE (
       SELECT COUNT(DISTINCE sal) 
       FROM emp b 
          


        
相关标签:
26条回答
  • 2020-11-30 07:50

    This will also work :

    with data as 
    (
    select sal,rwid from (
    select salary as sal,rowid as rwid from salary order by salary desc
    )
    where rownum < 5
    )
    select * from salary a 
    where rowid = (select min(rwid) from data)
    
    0 讨论(0)
  • 2020-11-30 07:51

    These queries will also work:

    Workaround 1)

    SELECT ename, sal 
    FROM Emp e1 WHERE n-1 = (SELECT COUNT(DISTINCT sal) 
                             FROM Emp e2 WHERE e2.sal > e1.sal)
    

    Workaround 2) using row_num function.

    SELECT * 
    FROM ( 
       SELECT e.*, ROW_NUMBER() OVER (ORDER BY sal DESC) rn FROM Emp e 
    ) WHERE rn = n;
    

    Workaround 3 ) using rownum pseudocolumn

    Select MAX(SAL) 
    from (
       Select * 
       from (
          Select * 
          from EMP 
          order by SAL Desc
       ) where rownum <= n
    )
    
    0 讨论(0)
  • 2020-11-30 07:52
    SELECT sal FROM (
        SELECT sal, row_number() OVER (order by sal desc) AS rn FROM emp
    )
    WHERE rn = 3
    

    Yes, it will take longer to execute if the table is big. But for "N-th row" queries the only way is to look through all the data and sort it. It will be definitely much faster if you have an index on sal.

    0 讨论(0)
  • 2020-11-30 07:52

    Try this one :

    Select sal 
    From (Select rownum as rank, empno,ename,sal
          From (Select * 
                From emp order by sal desc)
          ) 
    where rank=2;
    

    Just add the number as rank which will give you nth highest salary.

    0 讨论(0)
  • 2020-11-30 07:55

    select min(sal) from (select distinct sal from employee order by sal DESC) where rownum<=N;

    place the number whatever the highest sal you want to retrieve.

    0 讨论(0)
  • 2020-11-30 07:55
    SELECT Min(sal)
    FROM   (SELECT DISTINCT sal
            FROM   emp
            WHERE  sal IS NOT NULL
            ORDER  BY sal DESC)
    WHERE  rownum <= n;  
    
    0 讨论(0)
提交回复
热议问题