如果要获取以下方案的CSV值

时间:2011-01-17 13:08:02

标签: sql-server sql-server-2005

这是我当前的表数据。

AccountNumber         Product
------------------------------
00505871              Product1
00505871              Product2
00503297              Product3
00900004              Product4
00505871              Product3
00514884              Product3
00503297              Product2
00505871              Product1

如何实现以下结果。

AccountNumber        ProductString
------------------------------------------------
00505871             Product1,Product2,Product3
00503297             Product2,Product3
00900004             Product4
00514884             Product3

谢谢,

Ashish Chotalia

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:-2)

以下解决方案适合我。

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