Selecting the second row of a table using rownum

后端 未结 9 1510
栀梦
栀梦 2020-11-28 14:07

I have tried the below query:

select empno from (
                   select empno 
                     from emp
                    order by sal desc
               


        
9条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 15:00

    In the first query, the first row will have ROWNUM = 1 so will be rejected. The second row will also have ROWNUM = 1 (because the row before was rejected) and also be rejected, the third row will also have ROWNUM = 1 (because all rows before it were rejected) and also be rejected etc... The net result is that all rows are rejected.

    The second query should not return the result you got. It should correctly assign ROWNUM after ORDER BY.

    As a consequence of all this, you need to use not 2 but 3 levels of subqueries, like this:

    SELECT EMPNO, SAL FROM ( -- Make sure row is not rejected before next ROWNUM can be assigned.
        SELECT EMPNO, SAL, ROWNUM R FROM ( -- Make sure ROWNUM is assigned after ORDER BY.
            SELECT EMPNO, SAL
            FROM EMP
            ORDER BY SAL DESC
        )
    )
    WHERE R = 2
    

    The result:

    EMPNO                  SAL                    
    ---------------------- ---------------------- 
    3                      7813                   
    

提交回复
热议问题