Transpose some columns to rows using pivot with SQL

后端 未结 2 1134
孤独总比滥情好
孤独总比滥情好 2021-01-15 02:48

MS SQL Server 2012

I have a table called indexrows

name    displayname propertyvalue
abc      $row1        agg
abc      $row2                


        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-15 03:10

    PIVOTs need an aggregate function, because you could have multiple entries in the original table. If you know you only have one value per key, then just use MIN().

    Also, '$row1', '$row2', '$row3' are now columns and need to be delimited like columns

    select * 
    from (
      select 
      name,propertyvalue, displayname
      from indexrows
    ) a
    PIVOT 
    (
    MIN(propertyvalue)
    for [displayname] in ([$row1], [$row2], [$row3])
    ) as pivot
    

提交回复
热议问题