regexp_split_to_table and row_number

*爱你&永不变心* 提交于 2020-07-21 06:06:25

问题


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!


回答1:


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;



回答2:


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


来源:https://stackoverflow.com/questions/44117035/regexp-split-to-table-and-row-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!