[英]Combine all values in one column with the same ID with Comma Separated values in SQL Server
I have this current output: 我有这个当前输出:
ID | Date | Products
-------------------------------------
01 | 02-18-2015 | Product A
02 | 02-18-2015 | Product B
02 | 02-18-2015 | Product C
But I want to have this: 但是我想要这个:
ID | Date | Products
-------------------------------------
01 | 02-18-2015 | Product A
02 | 02-18-2015 | Product B, Product C
Some part of the code in SQL: 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
I hope someone can help me solve this specific problem. 我希望有人可以帮助我解决这个特定问题。
This could be done using FOR XML PATH()
这可以使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.