首页 > 解决方案 > 将逗号分隔的列数据拆分为多列(可变大小)

问题描述

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

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

进入

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

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

J.P

标签: sqlpostgresqlcsvsplit

解决方案


您可以使用 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;

推荐阅读