Using for XML in T-sql to pivot data

2019-06-03 14:40发布

问题:

I am attempting to use the for XML function to pivot some data. My data is as follows:

VenNum_A   VenNum_B
0001       0002
0001       0003
0001       0004
0005       0006
0005       0007
0005       0008

I am attempting to get the following result:

venNum_A   VenNum_B
0001       0002,0003,0004
0005       0006,0007,0008

My Code so far:

; with t as
        (
        select Distinct 
            A_VenNum, B_VenNum, SUM(1) as Cnt
        From 
            #VenDups_Addr
        Group by 
            A_VenNum, B_VenNum
        )
        select distinct
            B_Vennum,
             A_Vennum =cast(substring((
            select distinct 
                  [text()] =  ', ' + t1.A_Vennum 
            from 
                  t as t1
            where 
                t.A_Vennum =t1.A_VenNum
            for XML path('')
                ),3,99) as Varchar(254))

        From t  

Currently my results are no different than selecting both original fields.

Also if this is not the best method of reaching my end goal I am totally open to an alternate solution, This is the only way I know of doing this.

回答1:

Try

Declare @t table(VenNum_A VARCHAR(10),   VenNum_B VARCHAR(10))
Insert Into @t 
Select '0001','0002' Union All Select '0001','0003' Union All Select '0001','0004' Union All 
Select '0005','0006' Union All Select '0005','0007' Union All Select '0005','0008'

SELECT 
    VenNum_A
    ,VenNum_B = STUFF((Select ',' + CAST(VenNum_B AS VARCHAR(1000)) 
      FROM  @t t2 
      WHERE t1.VenNum_A = t2.VenNum_A
      FOR XML PATh ('')
      ),1,1,'')
FROM @t t1
GROUP BY t1.VenNum_A

//Result

VenNum_A    VenNum_B
0001    0002,0003,0004
0005    0006,0007,0008

Hope this helps



回答2:

Are you aware that CodePlex has an open-source CLR implementation of user defined aggregate GROUP_CONCAT .Installation is as simple as running a SQL script on your server.

http://groupconcat.codeplex.com/

it has 4 group_concat implementation

  • GROUP_CONCAT --default delimiter is , (comma)

  • GROUP_CONCAT_D -- you can specify the delimiter

  • GROUP_CONCAT_DS -- you can specify the delimiter ,sort order (1 as asc order ,2 as desc order)

  • GROUP_CONCAT_S -- you can specify sort order

In your example you will use it like this

SELECT  VenNum_A        
       ,dbo.GROUP_CONCAT(VenNum_B) AS VenNum_B        
FROM YourTable
GROUP BY
    VenNum_A