how to split a string in a column field value of a table to multiple rows in select query in postgresql

荒凉一梦 提交于 2021-02-05 07:54:09

问题


table1

ID     ITEM
-----------------------
1      a|b|c
2      x|y|z
3      Q||S
4      ||||
5      J|K|Y|U

I want to insert above ITEM to table2 as following manner

table2

SLNO  ID   ITEMS
------------------------
1      1    a
2      1    b
3      1    c
4      2    x
5      2    y
6      2    z
7      3    Q
8      3    S
9      5    J
10     5    K
11     5    Y
12     5    U

so i have used

INSERT INTO table2("ID","ITEMS")SELECT  ID,split_part("ITEM", '|',1) AS ITEMS FROM  table1

the problem is split_part() need to specify a postion index,so it only split and shows first positions charaters means,

ID  ITEMS
-----------
1   a
2   x
3   Q
5   J

So how i acheive above


回答1:


You can convert the string to an array, then unnest that array:

select t.id, i.item
from the_table t
  cross join unnest(string_to_array(t.items, '|')) as i(item);

If you want to exclude the empty elements (e.g. in the line 4 |||| you can use:

select t.id, i.item
from the_table t
  cross join unnest(string_to_array(t.items, '|')) as i(item)
where nullif(trim(i.item),'') is not null;

Online example



来源:https://stackoverflow.com/questions/59320433/how-to-split-a-string-in-a-column-field-value-of-a-table-to-multiple-rows-in-sel

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