简体   繁体   中英

Split a string column to new columns postgresql

I have a column which can contain over 20 different values and they are seprated by semicolon. for example: A;B;C;D;E;F;G;H;.... , I need to split all the values in new columns. I tried to split it with SPLIT_PART() , but it seems i need to sepcify which position do i want from the string. But in my case, there are too many values and it's not very effcient to do like this.

I wonder if there's anyway that I can split them by; and all value will be saved in a new column?

Split the string into an array and select array elements. A CTE stands for the table.
Here is an illustration for 10 columns. Still somewhat verbose but of a regular nature.

with the_table(s) as 
(
 values
 ('A01;B01;C01;D01;E01;F01;G01;H01;I01;J01'),
 ('A02;B02;C02;D02;E02;F02;G02;H02;I02;J02'),
 ('A03;B03;C03;D03;E03;F03;G03;H03;I03;J03')
),
arr(a) as 
(
 select string_to_array(s,';') from the_table
)
select 
  a[1] c1,a[2] c2,a[3] c3,a[4] c4,a[5]  c5,
  a[6] c6,a[7] c7,a[8] c8,a[9] c9,a[10] c10 -- ...
from arr;
c1 c2 c3 c4 c5 c6 c7 c8 c9 c10
A01 B01 C01 D01 E01 F01 G01 H01 I01 J01
A02 B02 C02 D02 E02 F02 G02 H02 I02 J02
A03 B03 C03 D03 E03 F03 G03 H03 I03 J03

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM