TSQL Pivot Long List of Columns

前端 未结 1 1226
后悔当初
后悔当初 2021-01-25 17:52

I am looking to use pivot function to convert row values of a column into separate columns. There are 100+ distinct values in that column and hard-coding each and every single v

相关标签:
1条回答
  • 2021-01-25 18:37

    You can use Dynamic SQL in a PIVOT for this type of query. Dynamic SQL will get the list of the items that you want to transform on execution which prevents the need to hard-code each item:

    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)
    

    See SQL Fiddle with Demo

    If you post a sample of data that you need to transform, then I can adjust my query to demonstrate.

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