Oracle 正则表达式行转列
原始的数据: aa,bb,cc,dd ee,ff,gg,hh 想要得到的结果: aa bb cc dd ... 先弄一条试试: SQL> with t as( select 1 id,'aa,dd' names from dual) select id,REGEXP_SUBSTR(names,'[^,]+',1,level) name, 'REGEXP_SUBSTR('''||names|| ',''[^,]+'','||level||')' exec_s from t connect by level <=regexp_count(names,',')+1 order by name; ID NAME EXEC_S ---- ------ -------------------------------------------- 1 aa REGEXP_SUBSTR('aa,dd,1) 1 bb REGEXP_SUBSTR('aa,2) 1 cc REGEXP_SUBSTR('aa,3) 1 dd REGEXP_SUBSTR('aa,4) 已用时间: 00: 00: 00.01 这么写发现结果集不对: SQL> with t as(select 1 id,dd' names from dual union all select 2 id,'ee,hh' names from dual ) select id, 'REGEXP_SUBSTR('''||names|| ',')+1 order by name; ID NAME EXEC_S --- ------ ---------------------------------------------- 1 aa REGEXP_SUBSTR('aa,2) 1 bb REGEXP_SUBSTR('aa,3) 1 cc REGEXP_SUBSTR('aa,4) 1 dd REGEXP_SUBSTR('aa,4) 2 ee REGEXP_SUBSTR('ee,hh,1) 2 ff REGEXP_SUBSTR('ee,2) 2 ff REGEXP_SUBSTR('ee,2) 2 gg REGEXP_SUBSTR('ee,3) 2 gg REGEXP_SUBSTR('ee,3) 2 hh REGEXP_SUBSTR('ee,4) 2 hh REGEXP_SUBSTR('ee,4) 已选择30行。 已用时间: 00: 00: 00.06 原因是多行的话产生了上下级关系: SQL> with t as( SQL> with t as( 改写: SQL> with t as(select 1 id,'||level||')' exec_s from t connect by prior names=names and level<=regexp_count(names,')+1 and prior SYS_GUID() is not null order by name; ID NAME EXEC_S ---- ------- --------------------------------------------- 1 aa REGEXP_SUBSTR('aa,1) 1 bb REGEXP_SUBSTR('aa,2) 1 cc REGEXP_SUBSTR('aa,3) 1 dd REGEXP_SUBSTR('aa,4) 2 ee REGEXP_SUBSTR('ee,1) 2 ff REGEXP_SUBSTR('ee,2) 2 gg REGEXP_SUBSTR('ee,3) 2 hh REGEXP_SUBSTR('ee,4) 已选择8行。 已用时间: 00: 00: 00.05 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |