从3个表中选择数据,而多个值应以逗号分隔

时间:2014-05-15 09:53:46

标签: sql sql-server sql-server-2008

我有以下3个表:

enter image description here .......
enter image description here ....... enter image description here .............................. .................................... ..............................

我运行以下查询

SELECT Employee.EmployeeId,
  EmployeeName,
  ProjectName
FROM Employee
JOIN ProjEmp
ON Employee.EmployeeId=ProjEmp.EmployeeId
JOIN Project
ON Project.ProjectId=ProjEmp.ProjectId

它给出了以下结果:

enter image description here

但我需要这样的结果:

enter image description here

建议我对所需结果的最佳查询。

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作以获得所需内容:

WITH CTE AS(SELECT Employee.EmployeeId,
  EmployeeName,
  ProjectName
FROM Employee
JOIN ProjEmp
ON Employee.EmployeeId=ProjEmp.EmployeeId
JOIN Project
ON Project.ProjectId=ProjEmp.ProjectId)

SELECT EmployeeId,EmployeeName,
      ProjectName = STUFF((
          SELECT ',' + convert(varchar(10),T2.ProjectName)
          FROM CTE T2
          WHERE T1.EmployeeName = T2.EmployeeName
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM CTE T1
GROUP BY EmployeeId,EmployeeName
ORDER BY EmployeeId

结果:

EMPLOYEEID   EMPLOYEENAME   PROJECTNAME
1            Emp1           ProjA,ProjB
3            Emp3           ProjC
4            Emp4           ProjC,ProjD
5            Emp5           ProjE
7            Emp7           ProjE
8            Emp8           ProjE

请参阅SQL Fiddle中的结果。