Postgresql以不同的方式记录

时间:2014-10-28 15:33:04

标签: postgresql

我有类似的记录

1|{4947583,4947582,4947581,4947580}
2|{4947590,4947589,4947588}
3|{4947613,4947612}

输入整数[]

我希望按此顺序拥有ID

4947583,4947590,4947613,4947582,4947589,4947612,4947581,4947588,4947580

2 个答案:

答案 0 :(得分:1)

WITH myvalues AS (
SELECT id, unnest(myarray) myvals
FROM (
VALUES (1,string_to_array('4947583,4947582,4947581,4947580', ',')),
    (2, string_to_array('4947590,4947589,4947588', ',')),
    (3, string_to_array('4947613,4947612', ',')) ) v (id, myarray)
    ),
iterated AS (SELECT *, row_number() OVER (PARTITION BY id)
FROM myvalues)
SELECT array_to_string(array( SELECT myvals
FROM iterated i1
ORDER BY row_number, id), ',')

为了清晰起见,这可能会有点熟,但它确实有效。

答案 1 :(得分:0)

假设1,2和3是行的一部分。 。

create table test (
  test_id serial primary key,
  ints integer[]
);

insert into test (ints) values ('{4947583,4947582,4947581,4947580}');
insert into test (ints) values ('{4947590,4947589,4947588}');
insert into test (ints) values ('{4947613,4947612}');

select test_id, unnest, row_number() over (partition by test_id order by unnest desc) 
from (select test_id, unnest(ints) from test) x 
order by row_number, test_id;
 test_id | unnest  | row_number
---------+---------+------------
       1 | 4947583 |          1
       2 | 4947590 |          1
       3 | 4947613 |          1
       1 | 4947582 |          2
       2 | 4947589 |          2
       3 | 4947612 |          2
       1 | 4947581 |          3
       2 | 4947588 |          3
       1 | 4947580 |          4

row_number()函数具有为每个数组生成从1开始的索引的效果。