来自Join的具有相同ID的T-SQL Concat 2行

时间:2017-04-24 09:13:50

标签: sql-server tsql

我目前正在使用SQL Server 2012上的T-SQL进行查询。我通过另一个表中的连接从表中收集了几个标题。我的表看起来像这样:

表项目:

scanf()

表ProjectResources

 ProjectId |
-----------+
1          |   
2          |   
3          |   

我的临时表中的所需输出应如下所示:

ResourceId |    Label      | ProjectId
-----------+---------------+-----------
2          |   Resource X  |  1 
3          |   Resource Y  |  1
4          |   Resource Z  |  2
5          |   Resource A  |  2
6          |   Resource X  |  3

我想用相同的ProjectId连接所有标签。我当前的查询如下所示:

ProjectId  |   Label                  |
-----------+--------------------------+
1          |   Resource X, Resource Y |
2          |   Resource Z, Resource A |
3          |   Resource X             |

不幸的是,我的查询为每个Resouce Label创建了一个新行。您是否知道如何为包含相同ProjectId的每个资源创建一个包含“concatinated”合并行的新临时表?

非常感谢!

2 个答案:

答案 0 :(得分:2)

你可以像这样使用For xml path, stuff

SELECT p.ProjectId,
     STUFF((     SELECT ', ' + pr.Label 
            FROM ProjectResources pr 
            WHERE  pr.ProjectId = p.ProjectId FOR XML PATH('')
           )
         ,1,2,'') as Label
FROM Project p

答案 1 :(得分:2)

CREATE TABLE #Table2
    ([ResourceId] int, [Label] varchar(10), [ProjectId] int)
INSERT INTO #Table2
    ([ResourceId], [Label], [ProjectId])
VALUES
    (2, 'Resource X', 1),
    (3, 'Resource Y', 1),
    (4, 'Resource Z', 2),
    (5, 'Resource A', 2),
    (6, 'Resource X', 3)
SELECT p.ProjectId,
     STUFF((     SELECT ', ' + pr.Label 
            FROM (select a.ProjectId,ResourceId,Label from #Table1 A join #Table2 B on a.ProjectId=b.ProjectId) pr 
            WHERE  pr.ProjectId = p.ProjectId FOR XML PATH('')
           )
         ,1,2,'') as Label
FROM (select a.ProjectId,ResourceId,Label from #Table1 A join #Table2 B on a.ProjectId=b.ProjectId) p
group by  p.ProjectId

output 

ProjectId  |   Label                  |
-----------+--------------------------+
1          |   Resource X, Resource Y |
2          |   Resource Z, Resource A |
3          |   Resource X             |