我有以下查询返回所有员工的薪水.这项工作完美但我需要收集额外的数据,我将聚合到一个单元格中(参见结果集2).
如何将数据聚合到逗号分隔列表中?有点像Sum所做的,但我需要一个字符串作为回报.
SELECT Employee.Id,SUM(Pay) as Salary FROM Employee INNER JOIN PayCheck ON PayCheck.EmployeeId = Employee.Id GROUP BY Employee.Id
结果集1
Employee.Id Salary ----------------------------------- 1 150 2 250 3 350
我需要:
结果集2
Employee.Id Salary Data ---------------------------------------------------- 1 150 One,Two,Three 2 250 Four,Five,Six 3 350 Seven
解决方法
对于sql Server 2005,请使用STUFF函数和FOR XML PATH:
WITH summary_cte AS ( SELECT Employee.Id,SUM(Pay) as Salary FROM Employee JOIN PayCheck ON PayCheck.EmployeeId = Employee.Id GROUP BY Employee.Id) SELECT sc.id,sc.salary,STUFF((SELECT ','+ yt.data FROM your_table yt WHERE yt.id = sc.id GROUP BY yt.data FOR XML PATH(''),TYPE).value('.','VARCHAR(max)'),1,'') FROM summary_cte sc
但是,您缺少有关要将数据转换为逗号分隔字符串的位置的详细信息,以及它与员工记录的关系…