使用stuff()
select id, stuff(( select concat( ',', name) from tablename b where a.id= b.id
for xml path('')),1,1, ''),count(*) as cnt
from tablename a
group by id
CREATE TABLE #Temp
(ID INT,NAME VARCHAR(50))
INSERT INTO #Temp(ID, [NAME])VALUES(1,'ABC')
INSERT INTO #Temp(ID, [NAME])VALUES(1,'EFG')
INSERT INTO #Temp(ID, [NAME])VALUES(2,'HIJ')
INSERT INTO #Temp(ID, [NAME])VALUES(2,'JKL')
INSERT INTO #Temp(ID, [NAME])VALUES(3,'MNO')
首先创建一个表。...
SELECT t.ID,STUFF(
(
SELECT ',' + s.NAME
FROM #Temp s
WHERE s.ID = t.ID
FOR XML PATH('')),1,1,'') AS NAME,COUNT(t.ID) AS COUNT
FROM #Temp AS t
GROUP BY ID
USE Stuff()