DB2将多行记录合并成一行
如:
CREATE TABLE LX_TMP1(ID VARCHAR(100),OLDNAME VARCHAR(100));
INSERT INTO LX_TMP1 VALUES('LUYONG','A');
INSERT INTO LX_TMP1 VALUES('LUYONG','B');
INSERT INTO LX_TMP1 VALUES('LU','1');
INSERT INTO LX_TMP1 VALUES('LU','3');
INSERT INTO LX_TMP1 VALUES('LU','5');
合并后效果如下:
LU 1,3,5
LUYONG A,B
有两种方法:
1、利用XML方法,百度多数说的是这种方法,前提是数据库支持XML
select ID,replace(replace(xml2clob(xmlagg(xmlelement(NAME A, OLDNAME||','))),'',''),'','') FROM
LX_TMP1 GROUP BY ID;
结果:
LU 1,3,5,
LUYONG A,B,
说明:按ID列归类,"NAME A" 与 '' 这两个A必须相同,OLDNAME是要连接的列。
2、利用递归方法
WITH LX_TMP2(ID,NEWOLDNAME,SN)
AS (
SELECT ID,OLDNAME,SN
FROM
(SELECT ID,OLDNAME,ROW_NUMBER() OVER(PARTITION BY ID ORDER BY OLDNAME ) AS SN FROM LX_TMP1 ) WHERE SN = 1
UNION ALL
SELECT T1.ID,T1.OLDNAME||','||T2.NEWOLDNAME AS NEWOLDNAME,T1.SN
FROM
(SELECT ID,OLDNAME,ROW_NUMBER() OVER(PARTITION BY ID ORDER BY OLDNAME ) AS SN FROM LX_TMP1 ) T1,
LX_TMP2 T2
WHERE T1.ID = T2.ID AND T1.SN = T2.SN + 1
)
SELECT ID,NEWOLDNAME FROM LX_TMP2 WHERE (ID,SN) IN
(
SELECT ID,MAX(SN)
FROM LX_TMP2
GROUP BY ID
);
结果:
LU 5,3,1
LUYONG B,A
说明:此方法是利用递归根据ID分类,然后标识序列,再根据序列把相同的字段字符相连。此方法还可以根据需求,排序相同字段的连接顺序。