利用FORXMLPATH行转列(根据某字段分组,多行数据转成一行,并用逗号隔开)

database

CREATE TABLE #TEST
(A VARCHAR(10) NULL,B VARCHAR(MAX) NULL)

INSERT INTO #TEST
SELECT "A","A001"
UNION ALL
SELECT "A","A002"
UNION ALL
SELECT "A","A003"
UNION ALL
SELECT "B","B001"
UNION ALL
SELECT "B","B002"

 

SELECT * FROM #TEST

 

--先来看一个简单的,效果如下图所示:

SELECT STUFF((SELECT ","+B FROM #TEST FOR XML PATH("")),1,1,"")

---------------------------------------------------------------

--再来个我们想要的,效果见下图:
SELECT DISTINCT t1.A,
REPLACE((SELECT B AS [data()] FROM #TEST t2 WHERE t1.A=t2.A FOR XML PATH(""))," ",",") AS B
FROM #TEST t1

---------------------------------------------------------------

以上是 利用FORXMLPATH行转列(根据某字段分组,多行数据转成一行,并用逗号隔开) 的全部内容, 来源链接: utcz.com/z/531729.html

回到顶部