0

我正在处理 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 

真的很感激这方面的帮助吗?

4

1 回答 1

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 Fiddle 与演示

如果您没有使用 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

SQL Fiddle 与演示

于 2013-05-30T08:43:37.810 回答