Selecting the second row of a table using rownum

后端 未结 9 1453
栀梦
栀梦 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 14:44
    Select * From (SELECT *,
      ROW_NUMBER() OVER(ORDER BY column_name  DESC) AS mRow
    
    FROM table_name 
    
    WHERE condition) as TT
    Where TT.mRow=2;
    
    0 讨论(0)
  • 2020-11-28 14:50

    You can use RANK or DENSE_RANK to achieve what you are trying to achieve here.

    0 讨论(0)
  • 2020-11-28 14:51

    To explain this behaviour, we need to understand how Oracle processes ROWNUM. When assigning ROWNUM to a row, Oracle starts at 1 and only increments the value when a row is selected; that is, when all conditions in the WHERE clause are met. Since our condition requires that ROWNUM is greater than 2, no rows are selected and ROWNUM is never incremented beyond 1.

    The bottom line is that conditions such as the following will work as expected.

    .. WHERE rownum = 1;

    .. WHERE rownum <= 10;

    While queries with these conditions will always return zero rows.

    .. WHERE rownum = 2;

    .. WHERE rownum > 10;

    Quoted from Understanding Oracle rownum

    You should modify you query in this way in order to work:

    select empno
    from
        (
        select empno, rownum as rn 
        from (
              select empno
              from emp
              order by sal desc
              )
        )
    where rn=2;
    

    EDIT: I've corrected the query to get the rownum after the order by sal desc

    0 讨论(0)
  • 2020-11-28 14:52

    select empno from(
    select empno,rownum as rum
    from emp,
    order by sal desc
    )
    where rum=2;

    0 讨论(0)
  • 2020-11-28 14:57

    Select Second Row From a Table in Oracle

    SELECT *
    FROM (SELECT * FROM emp ORDER BY rownum DESC)
    WHERE rownum=1
    
    0 讨论(0)
  • 2020-11-28 14:58

    try this way it's working 100% SQL> SELECT * FROM STUD;

    RNUMBER SNAME MARKS


       104 mahesh                       85
       101 DHANU                        20
       102 BHARATH                      10
       100 RAJ                          50
       103 GOPI                         65
    

    SQL> select * from(select MARKS,ROWNUM AS RS from ( select * from stud order by marks desc)) where RS=2;

     MARKS         RS
    

        65          2
    

    SQL>

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