Transpose some columns to rows using pivot with SQL

后端 未结 2 1141
孤独总比滥情好
孤独总比滥情好 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:11

    There are a few things are wrong with your query.

    First, you are missing an aggregate function on your PIVOT. You need an aggregate around propertyvalue.

    Second, you need to surround the $row1, etc with square brackets not single quotes.

    Third, I would use a different alias for the as pivot

    As a result the code will be:

    select * 
    from 
    (
      select name, propertyvalue, displayname
      from indexrows
    ) a
    pivot
    (
      max(propertyvalue)
      for [displayname] in ([$row1], [$row2], [$row3])
    ) piv;
    

    See SQL Fiddle with Demo

提交回复
热议问题