Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regexp_split_to_table and row_number

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!

like image 389
Cateh Avatar asked Dec 06 '22 14:12

Cateh


2 Answers

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;
like image 126
a_horse_with_no_name Avatar answered Dec 16 '22 18:12

a_horse_with_no_name


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
like image 45
Clodoaldo Neto Avatar answered Dec 16 '22 16:12

Clodoaldo Neto