Dynamic Pivot multiple columns in SQL Server

后端 未结 2 955
心在旅途
心在旅途 2021-01-26 11:55

I have a table like this

Id   Name   FromAddress   ToAddress
1    Joey      ABC          JKL
2    Joey      DEF          MNP
3    Joey      GHI          OQR
         


        
2条回答
  •  情深已故
    2021-01-26 12:33

    ok, I created a temp table to do some testing on. The solution requires an unpivot first. I recommend running with/without the extra test data to get a sense of some other behaviors that surround this solution -- the weirdness that comes with the MAX aggregation and lack of new rows that you might have expected when changing the value in 'name'.

    GL. Hope it helps.

    -------------------------
    -- Some test data here
    CREATE table #addresses ( Id int, Name varchar(5), FromAddress varchar(5), ToAddress varchar(5))
    insert into #addresses(id, Name, FromAddress, ToAddress) Values
    (1,'Joey', 'ABC', 'JKL')
    , (2,'Joey', 'DEF', 'MNO')
    , (3,'Joey', 'GHI', 'PQR')
    , (4,'Spike', 'XXX', 'YYY')
    , (1,'Spike', 'QQQ', 'RRR')
    
    -------------------------
    --  Solution starts here.  create a temp table and unpivot your data into it.
    --  Your initial technique of does not work, PIVOT only supports one aggregation
    
    CREATE table #unpvt(RowColCode varchar(20), vals varchar(20))
    Insert into #unpvt
    SELECT ColCode + '_' + Cast(ID as varchar(2)) as RowColCode, vals
    FROM #addresses a
    UNPIVOT
        (vals for ColCode in (Name,FromAddress,ToAddress)) c
    
    -------------------------
    --  Read the temp table for a column list
    
    declare @ColList nvarchar(max)
    set @ColList = STUFF((
        SELECT distinct ',[' + t.RowColCode + ']'
                FROM #unpvt t
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)'),1,1,'')
    
    
    -------------------------
    -- 're pivot' the data using your new column list
    
    declare @qry varchar(max)
    set @qry = '
    
    select *
    from
        #unpvt
        PIVOT(
        MAX(vals)
        FOR RowColCode in (' +@ColList +  ') 
        ) rslt
    '
    
    
    execute(@qry)  
    

提交回复
热议问题