Oracle以逗号分隔同一字段变成多列

 SELECT DISTINCT
T.ID,
REGEXP_SUBSTR (T.DEPTS, '[^,]+', 1, LEVEL) DEPT
FROM
VROADWORK_TROADWORKMAIN T CONNECT BY LEVEL <= LENGTH (T.DEPTS) - LENGTH (REPLACE(T.DEPTS, ',', '')) + 1
ORDER BY
T.ID;
T.DEPTS是要以逗号分隔的字段

 

方法一

SELECT DISTINCT
    F_STAFF_ID AS USER_ID,
    REGEXP_SUBSTR (F_STATION, '[^,]+', 1, LEVEL) as STATION_ID
FROM
    T_API_STAFF_POST CONNECT BY LEVEL <= LENGTH (F_STATION) - LENGTH (REPLACE(F_STATION, ',', '')) + 1
ORDER BY
    F_STAFF_ID;
 

方法二

 SELECT F_STAFF_ID as USER_ID,
       REGEXP_SUBSTR(F_STATION, '[^,]+', 1, lv) AS STATION_ID
  FROM T_API_STAFF_POST,
       (SELECT LEVEL lv FROM dual CONNECT BY LEVEL < 20) b
 WHERE b.lv <= REGEXP_COUNT(T_API_STAFF_POST.F_STATION, '\,') + 1
 ORDER BY F_STAFF_ID;

方法三

 SELECT F_STAFF_ID AS USER_ID,
       substr(a.F_STATION,
              instr(a.F_STATION, ',', 1, levels.lvl) + 1,
              instr(a.F_STATION, ',', 1, levels.lvl + 1) -
              (instr(a.F_STATION, ',', 1, levels.lvl) + 1)) as STATION_ID
  FROM (SELECT F_STAFF_ID,
               ',' || F_STATION || ',' AS F_STATION,
               length(F_STATION) - nvl(length(REPLACE(F_STATION, ',')), 0) + 1 AS cnt --取待拆分字段每行按照分隔符','分割后的记录数,用于connect by
          FROM T_API_STAFF_POST) a,
       (SELECT rownum AS lvl --产生一个待拆分字段分割后最大记录数的序列
          FROM (SELECT MAX(length(F_STATION || ',') -
                           nvl(length(REPLACE(F_STATION, ',')), 0)) max_len
                  FROM T_API_STAFF_POST)
        CONNECT BY LEVEL <= max_len) levels
 WHERE levels.lvl <= a.cnt --笛卡尔连接
 ORDER BY F_STAFF_ID;

性能上方法三最优,其次方法二,方法一因为有distinct,性能可想而知

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值