How to get second largest or third largest entry from a table

前端 未结 12 2454
说谎
说谎 2020-12-01 08:42

Can anyone please tell me how to find out the N th largest entry from a table in Oracle?

Like for largest we can use MAX(column_name) i

相关标签:
12条回答
  • 2020-12-01 09:18
    SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (
      SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal
    );
    

    Replace &N with you desired number. For example, 2 will give you the second largest salary.

    If you are using PL/SQL, just execute the statement. It will prompt for N.

    0 讨论(0)
  • 2020-12-01 09:19

    To get second largest salary use this:

    select salary from 
      (select s2.salary,rownum rm from
         (select distinct salary from employees order by salary desc)
      s2 where rownum<=2)
    where rm >= 2
    
    0 讨论(0)
  • 2020-12-01 09:23

    Try this:

    SELECT DISTINCT TOP 3 id,[Password] 
    FROM Users_changepassword 
    WHERE [UserId] = 3
    ORDER BY id DESC
    
    0 讨论(0)
  • 2020-12-01 09:26

    You can ORDER BY column name and then LIMIT 1,1 to get the second one

    edit

    Whoops, didn't see the Oracle tag, sorry.
    ORDER BY column name WHERE ROWNUM = 2 should work better.

    0 讨论(0)
  • 2020-12-01 09:27

    You can try this sql where Row_number() function of the oracle sql is used

    select column_name from (
     select column_name ,  
    row_number() over (order by column_name  desc) as  row_num  
    from table_Name ) tablex
    where row_num =3
    
    0 讨论(0)
  • 2020-12-01 09:28

    You could use CONNECT BY PRIOR by:

    CREATE TABLE t(i INT, sal INT);
    INSERT INTO t(i, sal)
    SELECT 1,100 FROM dual UNION
    SELECT 2,100 FROM dual UNION
    SELECT 3,200 FROM dual UNION
    SELECT 4,500 FROM dual UNION
    SELECT 5,1000 FROM dual;
    

    Query:

    SELECT level, MAX(sal) AS sal
    FROM t
    --WHERE level = 2 -- set position here
    CONNECT BY prior sal > sal
    GROUP BY level
    ORDER BY level;
    

    DBFiddle Demo

    DBFiddle Demo2


    EDIT:

    Second approach is to use NTH_VALUE analytic function:

    SELECT DISTINCT NTH_VALUE(sal, 2) OVER(ORDER BY sal DESC
           ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
    FROM t;
    

    DBFiddle Demo3

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