regexp_split_to_table和row_number

Cat*_*teh 2 postgresql split row-number

我有这样的表与字符串数据:

id | string_data
1  | red;green;blue
2  | orange
3  | purple;cyan
Run Code Online (Sandbox Code Playgroud)

我需要将字符串数据拆分为具有行号的项目:

id | num | item
1  | 1   | red
1  | 2   | green
1  | 3   | blue
2  | 1   | orange
3  | 1   | purple
3  | 2   | cyan
Run Code Online (Sandbox Code Playgroud)

我知道regexp_split_to_table(),但是将它与row_number()结合使用存在问题。有人知道如何解决这个问题吗?谢谢!

Clo*_*eto 5

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
Run Code Online (Sandbox Code Playgroud)


a_h*_*ame 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;
Run Code Online (Sandbox Code Playgroud)