简体   繁体   中英

oracle split comma delimited string into columns

I have a table like

Charge_num      mapping_col
---------       -----------
p1.pm.100       1.1.1,1000
p1.pm.110       1.2.1,1000
p1.pm.120       1.3.1,1000

I need to split the "mapping_col" into 2 columns like this:

Charge_num      wbs       obs
---------       ---       ---
p1.pm.100       1.1.1     1000
p1.pm.110       1.2.1     1000
p1.pm.120       1.3.1     1000
select charge_num, 
substr(mapping_col,1,instr(mapping_col,',',1)-1) AS first_half,
substr(mapping_col, instr(mapping_col,',',1)+1) as last_half
from your_table

Note that the practice of storing numbers as strings is prone to error. If you were to cast these results as NUMBER(9) it could break unpredictably if your data is irregular

REGEXP_SUBSTR to the rescue!

with sample_data as (select 'p1.pm.100' charge_num, '1.1.1,1000' mapping_col from dual union all
                     select 'p1.pm.110' charge_num, '1.2.1,1000' mapping_col from dual union all
                     select 'p1.pm.120' charge_num, '1.3.1,1000' mapping_col from dual)
select charge_num,
       regexp_substr(mapping_col, '[^,]+', 1, 1) wbs,
       regexp_substr(mapping_col, '[^,]+', 1, 2) obs
from   sample_data;

CHARGE_NUM WBS                            OBS                           
---------- ------------------------------ ------------------------------
p1.pm.100  1.1.1                          1000                          
p1.pm.110  1.2.1                          1000                          
p1.pm.120  1.3.1                          1000          

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