SQL Query With Row_Number, order by and where clause

后端 未结 5 1859
遥遥无期
遥遥无期 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: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).

提交回复
热议问题