Oracle行列轉換方法彙總
函式名:wmsys.wm_concat
作用:以逗號分隔連線列的值
oracle 10g引入。使用時直接用wm_concat也可以。
以下介紹一些實際使用的狀況。介紹實際Case前先建立一個測試table和一些測試資料。
兩張表: employee,prject;屬性如下
1)employee: 員工ID號,員工名,部門
測試資料
0001 user1 IT 0002 user2 IT
2)prject:專案ID號,負責的員工ID號
測試資料
PN001 0001 PN002 0001 PN003 0001 PN004 0001 PN010 0002 PN011 0002
對應的SQL如下
create table employee ( ID varchar(4) NOT NULL PRIMARY KEY, NAME varchar(20), DEPT varchar(20) ); create table prject ( PROJECTID varchar(5) NOT NULL PRIMARY KEY, OWNERID varchar(20) );
INSERT INTO employee(ID,NAME,DEPT) Values('0001','user1','IT'); INSERT INTO employee(ID,NAME,DEPT) Values('0002','user2','IT');
INSERT INTO prject(PROJECTID,OWNERID) Values('PN001','0001'); INSERT INTO prject(PROJECTID,OWNERID) Values('PN002','0001'); INSERT INTO prject(PROJECTID,OWNERID) Values('PN003','0001'); INSERT INTO prject(PROJECTID,OWNERID) Values('PN004','0001'); INSERT INTO prject(PROJECTID,OWNERID) Values('PN010','0002'); INSERT INTO prject(PROJECTID,OWNERID) Values('PN011','0002');
Case 1: 列轉換行。 以一行顯示所有員工的名字
select wmsys.wm_concat(NAME) from employee;
結果: user1,user2
Case 2: join 兩張table , 計算員工負責的 專案個數的例子.
select t1.ID,t1.DEPT,t2.pcount from (select ID,NAME,DEPT from employee) t1 left outer join (select OWNERID,trunc(length(replace(wm_concat(PROJECTID),',',''))/5) as pcount from prject group by OWNERID) t2 on t1.ID = t2.OWNERID;結果:
0001 IT 4 0002 IT 2
此Case如果使用Count替代的話也可以,而且寫法更簡單,但是table很複雜的時候使用count不能達成時,可以考慮這個方式, 此處附上count方式
select t1.ID,t1.DEPT,t2.pcount from (select ID,NAME,DEPT from employee) t1 left outer join (select OWNERID,count(PROJECTID) as pcount from prject group by OWNERID) t2 on t1.ID = t2.OWNERID;