我使用CTE做了一个例子,这里是
with CTE as
(
Select 'John' as Name, 'Book' as Product
Union all
Select 'John' as Name, 'Pen' as Product
Union all
Select 'John' as Name, 'Phone' as Product
Union all
Select 'Kevin' as Name, 'Book' as Product
Union all
Select 'Kevin' as Name, 'Watch' as Product
)
SELECT Name, Product=STUFF(
(SELECT ';' + Product FROM CTE t2
WHERE t1.Name = t2.Name
FOR XML PATH ('')) , 1, 1 , '')
FROM CTE t1
GROUP BY Name
如果你刚开始
select * from CTE
然后您将看到原始数据的外观如何
这是我在互联网上找到的一种方式,但首先我不明白它是如何工作的,如果有人能解释这项工作我非常感激 第二,有更简单的方法来实现我的目标吗?
谢谢!
答案 0 :(得分:0)
首先,这是您尝试做的最佳方式。与其他方法相比,它非常有效。让我解释它是如何工作的。
--So first your group by is grouping by name.
--It's really just getting the DISTINCT values of name
--You could actually use a distinct name instead of the group by clause
SELECT Name,
Product =
(
--This combines your semicolon to each value of product
SELECT ';' + Product
FROM CTE t2
--This connects this subquery to the outer query
WHERE t1.Name = t2.Name
--I don't know how this works exactly. It obviously uses some kind of XML parsing, but it concats all your rows together into one
FOR XML PATH ('')
)
FROM CTE t1
GROUP BY Name
结果:
Name Product
----- ----------------
John ;Book;Pen;Phone
Kevin ;Book;Watch
你会注意到我摆脱了STUFF(),告诉你它所做的就是删除第一个分号。如果你愿意,可以使用SUBSTRING()。
希望这会有所帮助。如果您还有其他需要,请告诉我。