Transpose some columns to rows using pivot with SQL

和自甴很熟 提交于 2019-12-01 08:25:34

问题


MS SQL Server 2012

I have a table called indexrows

name    displayname propertyvalue
abc      $row1        agg
abc      $row2        spx
abc      $row3        qqq
def      $row1        spx
def      $row2        qqq

I would like to transpose these results to look like this.

name    $row1   $row2   $row3
abc      agg    spx    qqq
def      spx    qqq 

I tried the following query without success. I get this error

Msg 156, Level 15, State 1, Line 10 Incorrect syntax near the keyword 'for'.

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

Any help is appreciated.


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/17458894/transpose-some-columns-to-rows-using-pivot-with-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!