Nth max salary in Oracle

前端 未结 26 1572
名媛妹妹
名媛妹妹 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:43

    Now you try this you will get for sure:

    SELECT DISTINCT sal 
        FROM emp a 
        WHERE (
               SELECT COUNT(DISTINCT sal) 
               FROM emp b 
               WHERE a.sal<=b.sal)=&n;
    

    For your information, if you want the nth least sal:

    SELECT DISTINCT sal 
    FROM emp a 
    WHERE (
           SELECT COUNT(DISTINCT sal) 
           FROM emp b 
           WHERE a.sal>=b.sal)=&n;
    
    0 讨论(0)
  • 2020-11-30 07:44

    you can replace the 2 with your desired number

    select * from ( select distinct (sal),ROW_NUMBER() OVER (order by sal desc) rn from emp ) where rn=2
    
    0 讨论(0)
  • 2020-11-30 07:44

    Try this:

    SELECT min(sal)  FROM (
    SELECT sal FROM emp ORDER BY sal desc) WHERE ROWNUM <= 3; -- Replace 3 with any value of N
    
    0 讨论(0)
  • 2020-11-30 07:46

    Refer following query for getting nth highest salary. By this way you get nth highest salary. If you want get nth lowest salary only you need to replace DESC by ASC in the query. for getting highest salary of employee.

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

    The following solution works from 12c onwards:

    Select min(sal) from emp where 
    Sal in ( select distinct (sal) from emp order by sal desc fetch first n rows only);
    

    Replace n as per your requirement

    0 讨论(0)
  • 2020-11-30 07:49
    SELECT * 
    FROM Employee Emp1
    WHERE (N-1) = ( 
    SELECT COUNT(DISTINCT(Emp2.Salary))
    FROM Employee Emp2
    WHERE Emp2.Salary > Emp1.Salary)
    
    0 讨论(0)
提交回复
热议问题