sql查询语句for xml path语法
for xml path作用:将多行的查询结果,根据某一些条件合并到一行。
例如:现在有一张表
执行下面语句
select [Department], (SELECT [Employee]+',' FROM dbo.[People] b WHERE b.[Department]=a.[Department] For XML Path('')) AS Student from [dbo].[People] as a group by [Department]
得到如下结果
可以,发现for xml path将,IT和人事的人员进行合并,并且用逗号进行分割。
如果想要获取整个公司的人员,并且用逗号隔开,执行如下语句
select STUFF((select ','+[Employee] FROM ( select [Employee] from dbo.[People] as a ) as c FOR XML PATH('')),1,1,'')
得到如下结果