SQL - 将多行数据组合到一行和一列

时间:2015-06-10 00:34:46

标签: sql-server for-xml-path

我希望创建一个SQL Server查询,它将使用三个表将具有相同Task的资源组合成一行/记录字符串。下面的我的SQL Server查询似乎没有正常工作,需要很长时间才能执行,然后出错。谢谢!

任务表

TaskUID
TaskName

作业表

TaskUID
ResourceUID

资源表

ResourceUID
ResourceName

之前

**Task Name     Resource Name**
Weapon Launch   Amy
Weapon Launch   Sam
Weapon Launch   Marisa
Weapon Launch   Katy
Weapon Launch   John
Sweating Tears  Marisa
Sweating Tears  Joe
Sweating Tears  Katy
Sweating Tears  Michael
Ramp Diver      Joe
Ramp Diver      Michael

**Task Name     Resource Name**
Weapon Launch   Amy; Sam; Marisa; Katy; John
Sweating Tears  Marisa; Joe; Katy; Michael
Ramp Diver      Michael; Joe

查询

SELECT T.TaskName,
STUFF(( SELECT ', ' + R.RESOURCENAME
FROM 
[Resource Table] R
LEFT JOIN [Assignment Table] A ON R.ResourceUID=A.ResourceUID
WHERE
A.TASKUID=T.TaskUID
Group by R.RESOURCENAME
FOR XML PATH('')), 1, 1,'') Resources
FROM [Task Table] T
INNER JOIN [Assignment Table] A ON T.TASKUID=A.TASKUID

2 个答案:

答案 0 :(得分:0)

请尝试:

SELECT T.TaskName, Resources
FROM TaskTable T
CROSS APPLY (
  SELECT 
    STUFF(( SELECT ', ' + R.RESOURCENAME
      FROM [ResourceTable] R
      INNER JOIN [AssignmentTable] A ON R.ResourceUID=A.ResourceUID
      WHERE A.TASKUID = T.TASKUID
      Group by R.RESOURCENAME
      FOR XML PATH('')), 1, 1,'') Resources
) N(Resources)

SQL Fiddle

答案 1 :(得分:0)

感谢Nizam,我发现我应该使用数据库中的表而不是视图,因为我没有创建索引的权限。内置索引允许更快的查询。

SELECT DISTINCT
T.TASK_NAME,
    STUFF((SELECT ', '+ R.RES_NAME
            FROM PUB.MSP_RESOURCES R
            JOIN PUB.MSP_ASSIGNMENTS A ON A.RES_UID=R.RES_UID
            WHERE A.TASK_UID=T.TASK_UID
            AND R.RES_TYPE IN(2)
            GROUP BY R.RES_NAME
            FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, '') AS RESOURCES