//a表:
c1 c2
22 a
25 b
26 c
46 d
//b表:
c3 c4
1 「22,25,26,46,」
//結果:
tb_c3 ta_c2
1 a,b,c,d
//分析:
//從結果可以看出來,這是乙個將行資料轉換為列資料的問題,可以根據b表中的c4列來連線a,b兩個表;
//現在的首要問題是,將b表中的c4列轉換為4個行,然後與a表進行等值連線;
//最後將上一步操作得到的資料,使用wm_concat()字串連線函式,在按照一定的類分組就可以得到結果
//解法一:
//1.首先將b表中的c4列轉換為行:
//這裡需要將c4列中的雙引號去掉(用空串來替換)
with tb as(
select 1 c3,'"22,25,26,46"' c4 from dual)
select c3,regexp_substr(replace(c4,'"',''),'[^,]+',1,level) c5
from tb
connect by
level <= length(replace(c4,'"','')) - length(replace(replace(c4,'"',''),',','')) + 1;
/ c3 c5
---------- ----------------------
1 22
1 25
1 26
1 46
//2.然後將第1不得到的結果與ta表進行等值連線:
with ta as(
select 22 c1, 'a' c2 from dual union all
select 25,'b' from dual union all
select 26,'c' from dual union all
select 46,'d' from dual)
, tb as(
select 1 c3,'"22,25,26,46"' c4 from dual)
select td.c3,ta.c2
from ta,(
select c3,regexp_substr(replace(c4,'"',''),'[^,]+',1,level) c5
from tb
connect by
level <= length(replace(c4,'"','')) - length(replace(replace(c4,'"',''),',','')) + 1) td
where ta.c1 = td.c5
/ c3 c2
---------- --
1 a
1 b
1 c
1 d
//3.使用wm_concat字串連線函式,將第2步得到的結果連線起來:
//這樣就能得到我們的結果了:
with ta as(
select 22 c1, 'a' c2 from dual union all
select 25,'b' from dual union all
select 26,'c' from dual union all
select 46,'d' from dual)
, tb as(
select 1 c3,'"22,25,26,46"' c4 from dual)
select te.a tb_c3,wm_concat(te.b) ta_c2
from (
select td.c3 a,ta.c2 b
from ta,(
select c3,regexp_substr(replace(c4,'"',''),'[^,]+',1,level) c5
from tb
connect by
level <= length(replace(c4,'"','')) - length(replace(replace(c4,'"',''),',','')) + 1) td
where ta.c1 = td.c5) te
group by a
/ tb_c3 ta_c2
---------- --------------
1 a,b,c,d
//解法二:
with ta as(
select 22 c1, 'a' c2 from dual union all
select 25,'b' from dual union all
select 26,'c' from dual union all
select 46,'d' from dual)
, tb as(
select 1 c3,'"22,25,26,46"' c4 from dual)
select c3,max(substr(sys_connect_by_path(c2,','),2)) a
from (
select c3,c2,rownum rn,rownum - 1 rm
from (
select a.c1,a.c2,b.c3,b.c4
from ta a,tb b)
where instr(c4,c1) > 0)
start with rn=1
connect by prior rn=rm
group by c3
/ c3 a
---------- ------------------
1 a,b,c,d
sqlServer 行列轉換之多行轉一行
記得在剛進專案組時候,使用oracle資料庫,遇到的第乙個難題就是行列轉換,哈哈,真是菜的一bi,現在使用sqlserver資料庫,又遇到了,記錄一下,以備後用和幫助後來者。言歸正傳 資料庫 sqlserver2008r2 英文版 1.建表 學生表 姓名,學科,成績 create table tes...
DB2行列轉換
在db2資料庫中常用函式講db2行列轉換 select column1,replace replace xml2clob xmlagg xmlelement name a,column2 as name1 form tablename where 1 0 group by column1 將不需要行...
oracle列轉換為行
首先介紹行轉換為列,oracle行轉換為列是比較常見,網上常見的例子如下 grades表 student subject grade student1 語文 80 student1 數學 70 student1 英語 60 student2 語文 90 student2 數學 80 student2...