问题
Here's my current table data.
AccountNumber Product
------------------------------
00505871 Product1
00505871 Product2
00503297 Product3
00900004 Product4
00505871 Product3
00514884 Product3
00503297 Product2
00505871 Product1
How can I achieve following result.
AccountNumber ProductString
------------------------------------------------
00505871 Product1,Product2,Product3
00503297 Product2,Product3
00900004 Product4
00514884 Product3
Thanks,
Ashish Chotalia
回答1:
select AccountNumber,
stuff((select ',' + Product
from YourTable t2
where t2.AccountNumber = t1.AccountNumber
order by Product
for xml path('')),1,1,'') as ProductString
from YourTable t1
group by AccountNumber
回答2:
Below solution worked for me.
1.
select AccountNumber,
stuff((select ',' + Product
from YourTable t2
where t2.AccountNumber = t1.AccountNumber
Group by Product
order by Product
for xml path('')),1,1,'') as ProductString
from YourTable t1
group by AccountNumber
2.
select AccountNumber,
stuff((select distinct ',' +Product
from YourTable t2
where t2.AccountNumber = t1.AccountNumber
group by Product
for xml path('')),1,1,'') as ProductString
from YourTable t1
group by AccountNumber
来源:https://stackoverflow.com/questions/4713476/how-to-get-csv-value-for-following-scenario