Oracle中的列轉行例子詳解


數據如下:
name id
張三 1,2,3

要求實現:
name id
張三 1
張三 2
張三 3

--創建臨時表
create table tmp as(select '張三' name, '1,2,3' id from dual);
--寫法1
select name,regexp_substr(id,'[^,]+',1,level) as id
from tmp
connect by level <= regexp_count(id,',')+1
order by id

--寫法2:
select name,trim(regexp_substr(id,'[^,]+',1,level)) as id
from tmp
connect by name = prior name 
and prior dbms_random.value is not null
and level <= length(regexp_replace(id, '[^,]'))+1;

--寫法3
select name,
--regexp_replace(id,'(\w+)\,(\w+)\,(\w+)',level) id
regexp_replace(id,'(\w+)\,(\w+)\,(\w+)','\'||to_char(level)) id
from tmp
connect by level <= regexp_count(id,',')+1;

--寫法4: 
select name,
substr(','||id||',',instr(','||id||',', ',', 1, level) + 1, instr(','||id||',', ',', 1, level + 1) -( instr(','||id||',', ',', 1, level) + 1))
from tmp
connect by level <= regexp_count(id,',')+1
order by level

此外,列轉行還可以使用union all和unpivot(oracle 11g新特性)等,待后續補充


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM