Nth max salary in Oracle

前端 未结 26 1574
名媛妹妹
名媛妹妹 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:37
    select min(sal) from (select distinct(sal) from emp  order by sal desc) where rownum <=&n;
    

    Inner query select distinct(sal) from emp order by sal desc will give the below output as given below.

    SAL 5000 3000 2975 2850 2450 1600 1500 1300 1250 1100 950 800

    without distinct in the above query select sal from emp order by sal desc output as given below.

    SAL 5000 3000 3000 2975 2850 2450 1600 1500 1300 1250 1250 1100 950 800

    outer query will give the 'N'th max sal (E.g) I have tried here for 4th Max sal and out put as given below.

    MIN(SAL) 2850

    0 讨论(0)
  • 2020-11-30 07:39
    SELECT TOP (1) Salary FROM
    (
        SELECT DISTINCT TOP (10) Salary FROM Employee ORDER BY Salary DESC
    ) AS Emp ORDER BY Salary
    

    This is for 10th max salary, you can replace 10 with n.

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

    5th highest salary:

    SELECT
        * 
    FROM
        emp a 
    WHERE 
        4 = (
            SELECT 
                COUNT(DISTINCT b.sal) 
            FROM 
                emp b 
            WHERE 
                a.sal < b.sal
        )
    

    Replace 4 with any value of N.

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

    Try out following:

    SELECT *
    FROM
      (SELECT rownum AS rn,
        a.*
      FROM
        (WITH DATA AS -- creating dummy data
        ( SELECT 'MOHAN' AS NAME, 200 AS SALARY FROM DUAL
        UNION ALL
        SELECT 'AKSHAY' AS NAME, 500 AS SALARY FROM DUAL
        UNION ALL
        SELECT 'HARI' AS NAME, 300 AS SALARY FROM DUAL
        UNION ALL
        SELECT 'RAM' AS NAME, 400 AS SALARY FROM DUAL
        )
      SELECT D.* FROM DATA D ORDER BY SALARY DESC
        ) A
      )
    WHERE rn = 3; -- specify N'th highest here (In this case fetching 3'rd highest)
    

    Cheers!

    0 讨论(0)
  • 2020-11-30 07:42
    Select min(salary) from (
      select distinct(salary) from empdetails order by salary desc
    ) where rownum <=&rn
    

    Just enter nth number which you want.

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

    You can optimize the query using Dense_rank() function.

    for Example :

    select distinct salary from ( select salary ,dense_rank() over (order by salary desc) ranking from Employee ) where ranking = 6

    Note: ranking 6 is the number of nth order.

    0 讨论(0)
提交回复
热议问题