使用带有SQL的数据透视表将某些列转置为行 [英] Transpose some columns to rows using pivot with SQL

查看:72
本文介绍了使用带有SQL的数据透视表将某些列转置为行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MS SQL Server 2012

MS SQL Server 2012

我有一个名为 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

第156条消息,第15级,状态1,第10行 关键字"for"附近的语法不正确.

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

感谢您的帮助.

推荐答案

您的查询有一些错误.

首先,您在PIVOT上缺少聚合函数.您需要围绕propertyvalue的汇总.

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

第二,您需要用方括号而不是单引号括住$row1等.

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

第三,我将为as pivot

因此,代码将是:

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

请参见带有演示的SQL提琴

这篇关于使用带有SQL的数据透视表将某些列转置为行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆