SQL Query With Row_Number, order by and where clause

后端 未结 5 1854
遥遥无期
遥遥无期 2021-01-21 03:33

I have the following SQL query:

select
     ID, COLUMN1, COLUMN2
from
     (select ID, COLUMN1, COLUMN2, row_number() over (order by 2 DESC) NO from A_TABLE)
whe         


        
相关标签:
5条回答
  • 2021-01-21 03:38

    Why don't you use

    Select top 100 ID, Column1, Column2
    From A_Table
    where Column1 like '%value%'
    order by Column2 desc
    
    0 讨论(0)
  • 2021-01-21 03:41

    Check out this Oracle FAQ. In particular this part:

      SELECT * 
      FROM (SELECT a.*, rownum RN 
          FROM (SELECT * 
                             FROM t1 ORDER BY key_column) a
             WHERE rownum <=7)
     WHERE rn >=5
    
    0 讨论(0)
  • 2021-01-21 03:47

    Here you will get the limited record from the oracle database without the usage of rownum

    select * from 
        ( select ,column1,column2,row_number() over (order by columnName) as rnum 
          from table_name) 
    where rnum between 5 and 10;
    
    0 讨论(0)
  • 2021-01-21 03:50

    rownum is a pseudo column that counts rows in the result set after the where clause has been applied.

    Is this what you're trying to get?

    SELECT *
    FROM ( 
        SELECT id, column1, column2
        FROM atable ORDER BY 2 DESC
    ) 
    WHERE ROWNUM < 100;
    

    Because it's a pseudo column that is strictly a counter of rows resulting from the where clause it will not allow you to do pagination (i.e. between 200 & 300).

    This is probably what you're looking for:

    SELECT *
    FROM
     (SELECT a.*, rownum rnum FROM
         (SELECT id, column1, column2 FROM atable ORDER BY 2 DESC) a WHERE rownum <= 300)
    WHERE rnum >= 200;
    
    0 讨论(0)
  • 2021-01-21 03:59

    To answer your first question: Don't use a column number in your order by clause, but use the column name. I don't fully understand your second question, because adding a WHERE in your most inner SELECT should do the trick:

    select ID
    ,      COLUMN1
    ,      COLUMN2
    from  (select ID
           ,      COLUMN1
           ,      COLUMN2
           ,      row_number() over (order by COLUMN1 DESC) NO
           from   A_TABLE
           where  COLUMNX LIKE '%SOME VALUE%'
          )
    where  NO between 0 and 100
    

    P.S. (to willcodejavaforfood) I think using row_number() is better when you want the rows to be ordered. It saves an inner view (big win for readability).

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