SQLserver 根据条件将多行合并为一行

将表和插入模拟数据

CREATE TABLE #TEST(
ID INT,
course VARCHAR(255)
)
INSERT INTO #TEST VALUES(1,'语文')
INSERT INTO #TEST VALUES(2,'数学')
INSERT INTO #TEST VALUES(3,'英语')
INSERT INTO #TEST VALUES(4,'英语')
INSERT INTO #TEST VALUES(4,'英语')
INSERT INTO #TEST VALUES(4,'英语1')

将course合并为一行

SELECT STUFF((
SELECT ',' +  course  FROM #TEST FOR XML PATH('')
),1,1,'') AS 科目

SQLserver 根据条件将多行合并为一行_第1张图片
将course合并为一行后,给对应ID,并去掉重复

select ID, name = (stuff((select ',' + course from (SELECT distinct course,ID FROM #TEST) BB where ID =   
a.ID for xml path('')),1,1,'')) from #TEST a group by ID

SQLserver 根据条件将多行合并为一行_第2张图片
sql:

select ID,
name = (
stuff(
(select ‘,’ + course from #TEST where ID = a.ID for xml path(‘’)),
1,
1,
‘’
)
) from #TEST a group by ID

关于stuff函数的应用以及 for xml path的应用可参见这两篇文章:
FOR XML PATH
stuff函数

你可能感兴趣的:(数据库,sqlserver,数据库,sql,for,xml,path)