我的表格包含如下字符串数据:
id | string_data
1 | red;green;blue
2 | orange
3 | purple;cyan
我需要将字符串数据拆分为带行号的项目:
id | num | item
1 | 1 | red
1 | 2 | green
1 | 3 | blue
2 | 1 | orange
3 | 1 | purple
3 | 2 | cyan
我知道regexp_split_to_table()但我有问题将它与row_number()结合起来。有人知道如何解决这个问题吗?谢谢!
答案 0 :(得分:5)
如果您不需要正则表达式,则使用string_to_array()
代替regexp_split_to_table()
会更有效。要获取数组索引,请使用with ordinality
select t.id,
x.idx,
x.word
from the_table t,
unnest(string_to_array(string_data, ';')) with ordinality as x(word, idx)
order by t.id, x.idx;
答案 1 :(得分:3)
select
id,
row_number() over (partition by id) as rn,
s
from (
select
id,
regexp_split_to_table(s, ';') as s
from t
) r
;
id | rn | s
----+----+--------
1 | 1 | red
1 | 2 | green
1 | 3 | blue
2 | 1 | orange
3 | 1 | purple
3 | 2 | cyan