I have table with string data like this:
id | string_data
1 | red;green;blue
2 | orange
3 | purple;cyan
And I need split string data to items with row numbers:
id | num | item
1 | 1 | red
1 | 2 | green
1 | 3 | blue
2 | 1 | orange
3 | 1 | purple
3 | 2 | cyan
I know regexp_split_to_table() but I have problem to combine it with row_number(). Does anybody know how to solve this? Thanks!
If you don't need a regex it's more efficient to use string_to_array()
instead of regexp_split_to_table()
. To get the array index, use 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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With