一条select语句将一个用逗分隔的列分成多行

本文介绍了一种使用WITH子句实现复杂字符串解析的高效SQL方法,包括使用笛卡尔积、子查询和函数来提取特定格式的数据。通过示例展示了如何在SQL中灵活处理和操作字符串数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文:http://www.itpub.net/thread-1284089-2-1.html

--下面的精妙sql!
with test1 as (
  select 1 as a,
        '1,2,3,4,5,6,7,8,9,9,8,8,8,8,7,6,5,4,5,6,7,8,9,0,-,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2' as label from dual
)
SELECT *
FROM
  (SELECT t1.a, 
          trim(SUBSTR(x2.label ,instr(x2.label, ',', 1, x2.rn) + 1, instr(x2.label, ',', 1, x2.rn + 1) - instr(x2.label, ',', 1, x2.rn) - 1)) label
  FROM test1 t1,
    (--笛卡尔积
    SELECT ','||t1.label||',' AS label,
          x1.rn
    FROM test1 t1,  ---!修改表名
      (--这里构成一个序列
      SELECT rownum rn
      FROM
        (SELECT MAX(LENGTH(t1.label) - LENGTH(REPLACE(t1.label, ','))) + 2 split_count --逗号的数量
        FROM test1 t1 ---!修改表名
        )
        CONNECT BY rownum <= split_count
      ) x1
    ) x2
  ) x3
WHERE x3.label IS NOT NULL
;


//====方法二

with hour_temp as
      (
          select '01,11,12' as col_hour
            from dual
      )
      select decode(a, 0, substr(hour, b), substr(hour, b, a - b)) as label
        from
        (
          select hour, instr(hour, ',', 1, lv) a,
                 lag(instr(hour, ',', 1, lv), 1, 0) over(order by lv) + 1 b
            from
            (
               select t.col_hour as hour, level as lv
                 from hour_temp t
              connect by level <=
                        length(t.col_hour) - length(replace(t.col_hour, ',', '')) + 1
             )
         );


 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值