我有以下查询,该查询返回所有员工的薪水。这项工作正常,但我需要收集将汇总到一个单元格中的额外数据(请参见结果集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, 1, '') FROM summary_cte sc
但是您缺少有关要转换为逗号分隔的字符串的数据的位置及其与员工记录的关系的详细信息…