工作和學習中常常會遇到一行要分割成多行數(shù)據(jù)的情況,在此整理一下做下對比。
單行拆分
如果表數(shù)據(jù)只有一行,則可以直接在原表上直接使用connect by+正則的方法,比如:
select regexp_substr('444.555.666', '[^.]+', 1, level) col
from dual
connect by level = regexp_count('444.555.666', '\.') + 1
輸出結果:
多行拆分
如果數(shù)據(jù)表存在多行數(shù)據(jù)需要拆分,也可以在原表上使用connect+正則的方法:
方法一
with t as
(select '111.222.333' col
from dual
union all
select '444.555.666' col
from dual)
select regexp_substr(col, '[^.]+', 1, level)
from t
connect by level = regexp_count(col, '\.\') + 1
and col = prior col
and prior dbms_random.value > 0
結果:
---------
111
222
333
444
555
666
方法二
使用構造的最大行數(shù)值關聯(lián)原表:
with t as
(select '111.222.333' col
from dual
union all
select '444.555.666' col
from dual)
select regexp_substr(col, '[^.]+', 1, lv)
from t, (select level lv from dual connect by level 10) b
where b.lv = regexp_count(t.col, '.') + 1
這種方法設置第二個數(shù)據(jù)集的時候要小于可能的最大值,然后兩數(shù)據(jù)集做關聯(lián),在做大數(shù)據(jù)量拆分的時候,這個數(shù)值設置得當,拆分行數(shù)相對一致的情況下,效率比方法一直接connect by要高。
方法三
使用table函數(shù):
with t as
(select '111.222.333' col
from dual
union all
select '444.555.666' col
from dual)
select column_value
from t,
table(cast(multiset
(select regexp_substr(col, '[^.]+', 1, level) dd
from dual
connect by level = regexp_count(t.col, '\.\') + 1) as
sys.odcivarchar2list)) a
結果:
COLUMN_VALUE
-------------
111
222
333
444
555
666
這個方法輸出的列名是固定的,column_value依賴于sys.odcivarchar2list這個類型的輸出,該方法對于大數(shù)據(jù)量的拆分效率比第二個方法好。
方法四
with t as
(select '111.222.333' col
from dual
union all
select '444.555.666' col
from dual)
select regexp_substr(col, '[^.]+', 1, trim(column_value))
from t,
xmltable(concat('1 to ',regexp_count(t.col, '.') + 1)) a ;
注意:大數(shù)據(jù)量的拆分時,謹慎使用正則的方法去做,可以使用substr+instr的方式替換正則。
如果以上方法的效率仍然不理想,可考慮使用plsql塊。
總結
以上就是本文關于Oracle數(shù)據(jù)行拆分多行方法示例的全部內容,希望對大家有所幫助。感興趣的朋友可以參閱:PLSQL Developer登錄的默認密碼介紹、ORACLE SQL語句優(yōu)化技術要點解析、淺談oracle rac和分布式數(shù)據(jù)庫的區(qū)別、oracle 數(shù)據(jù)庫啟動階段分析等。有什么問題可以隨時留言,歡迎大家交流討論。
您可能感興趣的文章:- Oracle以逗號分隔的字符串拆分為多行數(shù)據(jù)實例詳解