Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 为转置取消pivot枢轴_Sql Server_Pivot_Unpivot - Fatal编程技术网

Sql server 为转置取消pivot枢轴

Sql server 为转置取消pivot枢轴,sql-server,pivot,unpivot,Sql Server,Pivot,Unpivot,我有一个[账户名称],Q1,Q2…QN格式的账户表,其中包含每个账户的收入详细信息。需要将其转换为[Quarter][account1][account2] 我的问题如下 Select [Quarters], [account 1], [ account2] from ( Select * from Accounts unpivot ( Value for [Quarters] in (Q1,Q2,Q3,Q4,.....) ) unpiv ) as src Piv

我有一个[账户名称],Q1,Q2…QN格式的账户表,其中包含每个账户的收入详细信息。需要将其转换为[Quarter][account1][account2]

我的问题如下

Select [Quarters], [account 1], [ account2] 
from 
( 
  Select * 
  from Accounts
  unpivot 
  ( Value for [Quarters] in (Q1,Q2,Q3,Q4,.....) 
  ) unpiv
) as src
Pivot
(
   sum(value) for [Account name] in ([account1],[account2])
) piv 
但是这个查询返回空值

账目表

[Account name] [Q1] [Q2] [Q3]
   Apple        20   30   40
   Google       30   10   15
    IBM         34   23   12 
期望输出

[Quarters] [Apple][Google][IBM]
   Q1       20     30      34
   Q2       30     10      23
   Q3       40     15      12

可以使用UNPIVOT和PIVOT函数返回结果。我不确定为什么要返回null,可能是子查询中包含了太多的列。要获得结果,您应该能够使用:

select quarters, Apple, Google, IBM
from
(
  select accountname, quarters, value
  from accounts
  unpivot
  (
    value
    for quarters in (Q1, Q2, Q3)
  ) u
) d
pivot
(
  sum(value)
  for accountname in (Apple, Google, IBM)
) p;