简体   繁体   中英

how convert column to row and get its row_number in postgresql

I use select to some columns see the following example,

 select 55,5,8,3

and the result will be

在此处输入图片说明


so, how to convert this into rows and get the row_number of each ? like below

         row.number | col_val
        ------------+--------
              1       55
              2        5
              3        8
              4        3               
select *, 
       row_number() over ()
from unnest(array[55,5,8,3]);

although it is not guaranteed that the order is always the same (but in reality it is).

With the upcoming 9.4 version you can get a stable row number using the with ordinality option: http://www.postgresql.org/docs/9.4/static/queries-table-expressions.html#QUERIES-TABLEFUNCTIONS

For this purpose a_horse_with_no_name's answer is enough

or try something like this

select row_number() over() row_num,col_val from (
select unnest((
 select array[c1,c2,c3,c4] from (
select 55  c1,5 c2 ,8 c3,3 c4 )s 
)) as col_val) b

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