将以逗号分隔的列数据拆分为多个列(可变大小)

时间:2018-07-03 21:14:43

标签: sql postgresql csv split

需要一些帮助,将Postgres中的列数据(字符串)拆分为多个虚拟列,例如:

---------column-------
data1;data2;data3 -
data1;data3       -
data1             -

进入

- Col1 ---- Col2 ---- Col3
   1    |    1    |   1
   1    |    0    |   1
   1    |    0    |   0

我知道最大列数,因此可以预设虚拟列。我需要做某种for循环吗?

JP

1 个答案:

答案 0 :(得分:3)

您可以使用split_part():

select split_part(col, ';', 1) as col1, 
       split_part(col, ';', 2) as col2, 
       split_part(col, ';', 3) as col1
from the_table;

或更有效些,因为每行只进行一次拆分:

select c[1] as col1, 
       c[2] as col2, 
       c[3] as col3
from (
  select string_to_array(col, ';') as c
  from the_table
) t;
相关问题