How to create a PivotTable in Transact/SQL?

后端 未结 1 997
北海茫月
北海茫月 2020-11-27 22:24

My source data table is

MemID Condition_ID Condtion_Result
----------------------------------
1     C1           0
1     C2           0
1     C3           0
         


        
相关标签:
1条回答
  • 2020-11-27 23:11

    You need to use a PIVOT. You can use either a STATIC PIVOT where you know the values of the columns to transform or a DYNAMIC PIVOT where the columns are unknown until execution time.

    Static Pivot (See SQL Fiddle with Demo):

    select *
    from 
    (
        select memid, Condition_id, Condition_Result
        from t
    ) x
    pivot
    (
        sum(condition_result)
        for condition_id in ([C1], [C2], [C3], [C4])
    ) p
    

    Dynamic Pivot (See SQL Fiddle with Demo):

    DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)
    
    SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.condition_id) 
                FROM t c
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    
    
    set @query = 'SELECT memid, ' + @cols + ' from 
                (
                    select MemId, Condition_id, condition_result
                    from t
               ) x
                pivot 
                (
                    sum(condition_result)
                    for condition_id in (' + @cols + ')
                ) p '
    
    
    execute(@query)
    

    Both will generate the same results.

    0 讨论(0)
提交回复
热议问题