CREATE TABLE temp1(typeid int,NAME NVARCHAR(30));
INSERT INTO temp1 values(1,'张三');
INSERT INTO temp1 values(1,'李四');
INSERT INTO temp1 values(1,'王五');
INSERT INTO temp1 values(1,'赵六');
INSERT INTO temp1 values(2,'小明');
INSERT INTO temp1 values(2,'老王');
SELECT * FROM temp1
;WITH t1 AS (
SELECT typeid FROM temp1 GROUP BY typeid
)
SELECT A.typeid ,NAMES=STUFF((SELECT ','+LTRIM(NAME) FROM temp1 B WHERE B.typeid=a.typeid
FOR
XML PATH('')
),1,1,'')
FROM t1 A
INSERT INTO temp1 values(1,'张三');
INSERT INTO temp1 values(1,'李四');
INSERT INTO temp1 values(1,'王五');
INSERT INTO temp1 values(1,'赵六');
INSERT INTO temp1 values(2,'小明');
INSERT INTO temp1 values(2,'老王');
SELECT * FROM temp1
;WITH t1 AS (
SELECT typeid FROM temp1 GROUP BY typeid
)
SELECT A.typeid ,NAMES=STUFF((SELECT ','+LTRIM(NAME) FROM temp1 B WHERE B.typeid=a.typeid
FOR
XML PATH('')
),1,1,'')
FROM t1 A
DROP TABLE temp1