大数据-玩转数据-oracel字符串分割转化为多列

一、建表

create table split_string_test(
  id integer  primary key,
  test_string varchar2(500)
);

二、插入测试数据

insert into split_string_test values(1, '10,11,12,13,14,22');
insert into split_string_test values(2, '22,23,24');
insert into split_string_test values(3, '6,7,8,9');

三、语句

WITH  cntr  AS
( SELECT  LEVEL  AS lvl
  FROM  dual
  CONNECT BY  LEVEL  <= 1 +  (
          SELECT  MAX ( length(a.test_string) - length(replace(a.test_string, ',')) + 1) 
          FROM  split_string_test a
          )                
) 
SELECT  b.id, b.test_string , lvl, REGEXP_SUBSTR( b.test_string, '([^,]+)', 1, lvl)  AS split_str
FROM  split_string_test b , cntr 
where  (lvl  <=  length(b.test_string) - length(replace(b.test_string, ',')) + 1)
and (REGEXP_SUBSTR  ( b.test_string, '([^,]+)', 1, lvl)  IS NOT NULL
OR  b.test_string  IS NULL )
ORDER BY  b.id, lvl;

注:取字符串分拆最大的数

SELECT  MAX ( length(a.test_string) - length(replace(a.test_string, ',')) + 1)  FROM  split_string_test a

或:

SELECT b.id,
       b.test_string,
       lvl,
       REGEXP_SUBSTR(b.test_string, '([^,]+)', 1, lvl) AS split_str
  FROM split_string_test b,
       (SELECT LEVEL AS lvl
          FROM dual
        CONNECT BY LEVEL <= 1 + (SELECT MAX(length(a.test_string) -
                                            length(replace(a.test_string, ',')) + 1)
                                   FROM split_string_test a))
 where (lvl <=
       length(b.test_string) - length(replace(b.test_string, ',')) + 1)
   and (REGEXP_SUBSTR(b.test_string, '([^,]+)', 1, lvl) IS NOT NULL OR
       b.test_string IS NULL)
 ORDER BY b.id, lvl;

四、结果

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值