简体   繁体   English

T-SQL中行的串联

[英]Concatenation of rows in T-SQL

I use SQL Server 2008 and I have to three tables, products, producttags and tags. 我使用SQL Server 2008,我必须有三个表,产品,产品标签和标签。

Products
-----------------
Id | Name

ProductTags 
------------------
Id | ProductId | TagId

Tags
------------------
Id | Name

I'm trying to create query that returns a result that contains the product id in the first column and the name of the tags associated with the product concatenated in the second column, like this: 我正在尝试创建查询,该查询返回包含第一列中的产品ID的结果以及与第二列中连接的产品关联的标记的名称,如下所示:

productid | Tags
-------------------------------------
1           tag1, tag2, tag3
2           tag2, tag3

I know this can be accomplished with FOR XML PATH('') in some way, but I just can get it right. 我知道这可以通过某种方式使用FOR XML PATH('')来完成,但我能说得对。 Using FOR XML is not important. 使用FOR XML并不重要。 Any solution that will produce the result will do. 任何能产生结果的解决方案都可以。

SELECT
     c.ID, c.Name ProductName,
     STUFF(
         (SELECT    ',' + b.name
          FROM  ProductTags a
                INNER JOIN Tags b
            ON a.TagID = b.ID
          WHERE  a.ProductID = c.ID
          FOR XML PATH (''))
          , 1, 1, '')  AS TagListList
FROM Products AS c
GROUP BY c.Name, c.ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM