2013-05-30 182 views
0

我正在使用TSQL存儲過程,我需要將臨時表列轉換爲行。目前我正在逐一使用更新表,但我認爲使用pivot和unpivot可以輕鬆實現。SQL Server將行轉換爲列

數據源

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

我檢查了https://www.simple-talk.com/sql/t-sql-programming/switching-rows-and-columns-in-sql/它包含一些解決方案,但仍然無法匹配這個。 – LittleOne

+1

http://stackoverflow.com/questions/15662382/sql-server-exact-table-transpose – AakashM

回答

1

正如你指出這是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

+0

謝謝伊恩。似乎這應該適用於我的問題。我會檢查。 – LittleOne

+0

我正在使用SQL 2005版本和第二個爲我工作。謝謝。 – LittleOne