• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

使用带有 SQL 的数据透视表列转置为行

用户头像
it1352
帮助1

问题说明

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

感谢任何帮助.

正确答案

#1

您的查询有一些问题.

首先,您在 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 Fiddle with Demo

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcgfkjk
系列文章
更多 icon
同类精品
更多 icon
继续加载