您好,登錄后才能下訂單哦!
建一個Employee表,有兩個列,一個是name,一個是所屬于的部門(dept)
CREATE TABLE Employee(name VARCHAR(15),dept VARCHAR(15));
insert into Employee values('Jack','L3');
insert into Employee values('Lily','Quality');
insert into Employee values('Mark','ID');
insert into Employee values('Lee','L3');
insert into Employee values('Serge','Solutions');
insert into Employee values('John','Development');
insert into Employee values('Miso','Solutions');
insert into Employee values('Berni','Solutions');
select * from Employee;
NAME DEPT
----- -----------
Jack L3
Lily Quality
Mark ID
Lee L3
Serge Solutions
John Development
Miso Solutions
Berni Solutions
現在想寫一個SQL,把一個部門的員工給做統計,每個部門一行
數據變成下面的樣子
DEPT NAMES
----------- ----------------
Development John
ID Mark
L3 Jack,Lee
Quality Lily
Solutions Berni,Miso,Serge
實現的SQL
SELECT Dept
,SUBSTR(Names, 1, LENGTH(names) - 1)
FROM (
SELECT Dept
,REPLACE(REPLACE(XMLSERIALIZE(CONTENT XMLAGG(XMLELEMENT(NAME a, NAME) ORDER BY NAME) AS VARCHAR(60)), '
', ''), '
', ',') AS Names
FROM Employee
GROUP BY Dept
) AS X;
解釋幾個DB2 XML方法的含義
XMLELEMENT是把標量轉成XML的格式
select Dept,XMLELEMENT(NAME a, NAME) from Employee;
DEPT 2
----------- ------------
L3
Jack
Quality
Lily
ID
Mark
L3
Lee
Solutions
Serge
Development
John
Solutions
Miso
Solutions
Berni
XMLAGG把多個XML進行聚合,這里要給出分組的列(Dept),并且每個組里,以NAME進行排序
select Dept,XMLAGG(XMLELEMENT(NAME a, NAME) ORDER BY NAME) from Employee GROUP BY Dept;
DEPT 2
----------- -----------------------------------
Development
John
ID
Mark
L3
Jack
Lee
Quality
Lily
Solutions
Berni
Miso
Serge
XMLSERIALIZE()的作用是把XML轉換成為一個String類型
select Dept,XMLSERIALIZE(CONTENT XMLAGG(XMLELEMENT(NAME a, NAME) ORDER BY NAME) AS VARCHAR(60)) from Employee GROUP BY Dept;
DEPT 2
----------- -----------------------------------
Development
John
ID
Mark
L3
Jack
Lee
Quality
Lily
Solutions
Berni
Miso
Serge
到了這個地方就很簡單了,把
干掉,把
轉化成,即可
后來,出現了XMLGROUP,使用起來也比較方便
SELECT Dept
,XMLGROUP(',' || NAME AS a ORDER BY NAME)
FROM Employee
GROUP BY Dept
DEPT 2
----------- ----------------------------------------------------------------------------------------
Development
,John
ID
,Mark
L3
,Jack
,Lee
Quality
,Lily
Solutions
,Berni
,Miso
,Serge
SELECT Dept
,XMLCAST(XMLGROUP(',' || NAME AS a ORDER BY NAME) AS VARCHAR(60))
FROM Employee
GROUP BY Dept
DEPT 2
----------- -----------------
Development ,John
ID ,Mark
L3 ,Jack,Lee
Quality ,Lily
Solutions ,Berni,Miso,Serge
SELECT Dept
,SUBSTR(XMLCAST(XMLGROUP(',' || NAME AS a ORDER BY NAME) AS VARCHAR(60)), 2) AS Names
FROM Employee
GROUP BY Dept
DEPT NAMES
----------- ----------------
Development John
ID Mark
L3 Jack,Lee
Quality Lily
Solutions Berni,Miso,Serge
到了DB2 9.7.4之后,這個問題得到了完美的解決
SELECT Dept,
LISTAGG(name, ',')
WITHIN GROUP (ORDER BY name)
FROM Employee
GROUP BY Dept;
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。