我有以下3个表:
.......
.......
.............................. .................................... ..............................
我运行以下查询
SELECT Employee.EmployeeId,
EmployeeName,
ProjectName
FROM Employee
JOIN ProjEmp
ON Employee.EmployeeId=ProjEmp.EmployeeId
JOIN Project
ON Project.ProjectId=ProjEmp.ProjectId
它给出了以下结果:
但我需要这样的结果:
建议我对所需结果的最佳查询。
答案 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中的结果。