Transpose rows to columns based on ID column

前端 未结 1 1564
孤独总比滥情好
孤独总比滥情好 2020-12-21 13:38

I\'m currently running SQL Server 2008 and trying to get the following subquery data:

ID | Field Name | Field Selection
1  |  Rating 1  |      Good
1  |  Rat         


        
相关标签:
1条回答
  • 2020-12-21 13:54

    you can use SQL Server pivot clause for this:

    select
        p.*
    from Table1
    pivot(
        max([Field Selection])
        for [Field Name] in ([Rating 1], [Rating 2], [Rating 3])
    ) as p
    

    or you can pivot manually:

    select
        ID,
        max(case when [Field Name] = 'Rating 1' then [Field Selection] end) as [Rating 1], 
        max(case when [Field Name] = 'Rating 2' then [Field Selection] end) as [Rating 2],
        max(case when [Field Name] = 'Rating 3' then [Field Selection] end) as [Rating 3]
    from Table1
    group by ID
    

    sql fiddle demo

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