我正在研究TSQL存储过程,我需要将临时表列转换为行。目前我正在逐个使用更新表,但我认为使用pivot和unpivot这可以很容易地实现。
数据来源:
Periods Stat1 Stat2 Stat3 Stat4
--------------------------------------------------------
Value1 1.011 1.012 1.013 1.014
Value2 1.011 1.021 1.031 1.041
Value3 1.011 2.211 1.311 1.411
预期输出:
Stats Value1 Value2 Value3
-----------------------------------------------
Stat1 1.011 1.011 1.011
Stat2 1.012 1.021 1.211
Stat3 1.013 1.031 1.311
Stat4 1.014 1.041 1.411
真的很感激任何帮助吗?
答案 0 :(得分:1)
正如您所指出的那样,这是一个非透视然后转动数据的过程:
with statTable as
(
select periods = 'Value1', Stat1 = 1.011, Stat2 = 1.012, Stat3 = 1.013, Stat4 = 1.014
union all select 'Value2', 1.011, 1.021, 1.031, 1.041
union all select 'Value3', 1.011, 2.211, 1.311, 1.411
)
, up as
(
select periods,
c.[Stats],
c.value
from statTable
cross apply
(
values ('Stat1', Stat1), ('Stat2', Stat2), ('Stat3', Stat3), ('Stat4', Stat4)
) c ([Stats], value)
)
select [Stats],
Value1,
Value2,
Value3
from up
pivot
(
sum(value)
for periods in (Value1, Value2, Value3)
) p
如果您不使用SQL Server 2008或更高版本,则可以使用UNPIVOT代替CROSS APPLY:
with statTable as
(
select periods = 'Value1', Stat1 = 1.011, Stat2 = 1.012, Stat3 = 1.013, Stat4 = 1.014
union all select 'Value2', 1.011, 1.021, 1.031, 1.041
union all select 'Value3', 1.011, 2.211, 1.311, 1.411
)
, up as
(
select periods,
up.[Stats],
up.value
from statTable
unpivot
(
value
for [Stats] in (Stat1, Stat2, Stat3, Stat4)
) up
)
select [Stats],
Value1,
Value2,
Value3
from up
pivot
(
sum(value)
for periods in (Value1, Value2, Value3)
) p