HOw to get CSV value for following scenario

微笑、不失礼 提交于 2019-12-24 01:45:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!