Sometimes we need to put data in the same line and separate them with separators such as commas. Before, we usually used for xml path to achieve this. After 2017, the newly added STRING_AGG function can solve this problem. Test data :
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([name] nvarchar(22),[food] nvarchar(22))
Insert #T
select N'张三',N'馒头' union all
select N'张三',N'鸡蛋' union all
select N'张三',N'粥' union all
select N'李四',N'鸡腿' union all
select N'李四',N'米饭'
Go
--测试数据结束
result:
STRING_AGG is used as follows:
Select name,STRING_AGG(food,',') food from #T GROUP BY name
result: