正如你指出這是unpivoting然後旋轉數據的過程:
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 with demo。
如果你不使用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 with demo。
我檢查了https://www.simple-talk.com/sql/t-sql-programming/switching-rows-and-columns-in-sql/它包含一些解決方案,但仍然無法匹配這個。 – LittleOne
http://stackoverflow.com/questions/15662382/sql-server-exact-table-transpose – AakashM