将一列中的所有值与SQL Server中的逗号分隔值相同的ID组合在一起

时间:2015-03-10 04:28:06

标签: sql sql-server

我有这个当前的输出:

ID   |  Date            | Products  
-------------------------------------  
01   |  02-18-2015      | Product A
02   |  02-18-2015      | Product B
02   |  02-18-2015      | Product C

但我想要这个:

ID   |   Date        | Products  
-------------------------------------  
01   |  02-18-2015   | Product A
02   |  02-18-2015   | Product B, Product C

SQL中的部分代码:

SELECT  * 
INTO #tempA
FROM
    (SELECT 
        INV.ID, INV.Date
     FROM
        TblA INV) a

SELECT
    b.ID, b.Date, b.Products
INTO #tempB
FROM
    (SELECT  z.ID,z.Date,z.Products
       FROM
           (SELECT
                #tempA.ID, #tempA.Date, PR.Items AS Products 
            FROM #tempA
            INNER JOIN Items PR ON ...   ) z
    ) b

我希望有人可以帮我解决这个具体问题。

1 个答案:

答案 0 :(得分:1)

可以使用FOR XML PATH()

完成此操作
WITH SampleData(ID, Date, Products) AS(
    SELECT '01', '02-18-2015', 'Product A' UNION ALL
    SELECT '02', '02-18-2015', 'Product B' UNION ALL
    SELECT '02', '02-18-2015', 'Product C' 
)
SELECT
    t1.ID,
    t1.Date,
    Products = STUFF((
        SELECT ', ' + t2.Products
        FROM SampleData t2
        WHERE t1.Date = t2.Date
        AND t1.ID = t2.ID
        FOR XML PATH('')
    ),1, 2, '')
FROM SampleData t1
GROUP BY t1.ID, t1.Date