我的格式为Accounts
,[account name]
,Q1
.... Q2
的{{1}}表格,其中包含针对每个帐户的收入明细。需要将其转置为QN
[Quarter ]
[account1]
。
我的查询如下。
[account2]
但是这个查询返回NULL。
帐户表
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
答案 0 :(得分:0)
您可以同时使用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;