有表结构如下:
这时,要求显示所有学生的爱好的结果集,代码如下:
SELECT B.name,LEFT(StuList,LEN(StuList)-1) as hobby FROM ( SELECT name, (SELECT hobby+',' FROM student WHERE name=A.name FOR XML PATH('')) AS StuList FROM student A GROUP BY name ) B
结果:
因为有特殊字符,所以转义了,不转义使用 ,TYPE).value('.','NVARCHAR(MAX)'),如下:
SELECT B.name,LEFT(StuList,LEN(StuList)-1) as hobby FROM ( SELECT name, (SELECT hobby+',' FROM student WHERE name=A.name FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)') AS StuList FROM student A GROUP BY name ) B
结果: