Combine multiple rows into multiple columns dynamically in SQL Server

前端 未结 2 1242
轮回少年
轮回少年 2020-12-24 09:15

I have a large database table on which I need to perform the action below dynamically using Microsoft SQL Server.

From a result like this:

 badge   |         


        
2条回答
  •  情歌与酒
    2020-12-24 10:02

    I would do it using dynamic sql, but this is (http://sqlfiddle.com/#!6/a63a6/1/0) the PIVOT solution:

    SELECT badge, name, [AP_KDa], [AP_Match], [ADC_KDA],[ADC_Match],[TOP_KDA],[TOP_Match] FROM
    (
    SELECT badge, name, col, val FROM(
     SELECT *, Job+'_KDA' as Col, KDA as Val FROM @T 
     UNION
     SELECT *, Job+'_Match' as Col,Match as Val  FROM @T
    ) t
    ) tt
    PIVOT ( max(val) for Col in ([AP_KDa], [AP_Match], [ADC_KDA],[ADC_Match],[TOP_KDA],[TOP_Match]) ) AS pvt
    

    Bonus: This how PIVOT could be combined with dynamic SQL (http://sqlfiddle.com/#!6/a63a6/7/0), again I would prefer to do it simpler, without PIVOT, but this is just good exercising for me :

    SELECT badge, name, cast(Job+'_KDA' as nvarchar(128)) as Col, KDA as Val INTO #Temp1 FROM Temp 
    INSERT INTO #Temp1 SELECT badge, name, Job+'_Match' as Col, Match as Val FROM Temp
    
    DECLARE @columns nvarchar(max)
    SELECT @columns = COALESCE(@columns + ', ', '') + Col FROM #Temp1 GROUP BY Col
    
    DECLARE @sql nvarchar(max) = 'SELECT badge, name, '+@columns+' FROM #Temp1 PIVOT ( max(val) for Col in ('+@columns+') ) AS pvt'
    exec (@sql)
    
    DROP TABLE #Temp1
    

提交回复
热议问题