SQL2005以上
用到两个方法 stuff 和 for xml path
stuff :
stuff(param1, startIndex, length, param2)
说明:将param1中自startIndex(SQL中都是从1开始,而非0)起,删除length个字符,然后用param2替换删掉的字符
for xml path:
它就是将查询结果集以XML形式展现
l两个方法组合就可以将多行合并
具体的SQL:
SELECT DISTINCT
VisitID ,
STUFF(( SELECT ',' + DiagDesc
FROM dbo.Pat_Diagnose
WHERE VisitID = a.VisitID
FOR
XML PATH('')
), 1, 1, '') AS DiagDesc
FROM dbo.Pat_Diagnose AS a;