简体   繁体   中英

row_number() over() combined with order by

How can I add a sequential row number to a query that is using order by?

Let say I have a request in this form :

SELECT row_number() over(), data
FROM myTable
ORDER BY data

This will produce the desired result as rows are ordered by "data", but the row numbers are also ordered by data. I understand this is normal as my row number is generated before the order by, but how can I generate this row number after the order by?

I did try to use a subquery like this :

SELECT row_number() over(ORDER BY data), *
FROM
(  
   SELECT data 
   FROM myTable
   ORDER BY data
) As t1

As shown here , but DB2 doesn't seem to support this syntax SELECT ..., * FROM

Thanks !

You also need to use alaias name before '*'

SELECT row_number() over(ORDER BY data), t1.*
FROM
(  
   SELECT data 
   FROM myTable
   ORDER BY data
) As t1

You don't need a subquery to do this,

   SELECT data , row_number() over(ORDER BY data) as rn
   FROM myTable
   ORDER BY data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM