2017-04-09 89 views
-1

我有一個表:是否有可能使用SQL「unpivot」表?

id amount Y2016 Y2017 Y2018 
1 100    1  1 
2 200   
3 300  2  
4 400  2  3 
5 500      1 

,需要逆轉置並作出(多年乘「量」數據),一些計算結果 表:

id year amount 
1 Y2017 100 
1 Y2018 100 
3 Y2016 600 
4 Y2016 800 
4 Y2017 1200 
5 Y2018 500 

這可能嗎?如何?

+2

您應該將您的問題 - 一般來說 - 與您正在使用的數據庫進行標記。 –

+0

Actualy它只是用於Excel的加載項,可以爲Excel表格運行SQL。 – FFire

回答

1

最簡單的方式是使用union all

select id, 'Y2016' as year, Y2016 * amount as amount 
from t 
where Y2016 is not null 
union all 
select id, 'Y2017' as year, Y2017 * amount as amount 
from t 
where Y2017 is not null 
union all 
select id, 'Y2018' as year, Y2018 * amount as amount 
from t 
where Y2018 is not null; 

還有其他的方法(有些取決於數據庫)。但對於你的數據,這應該沒問題。

+0

如果我有大片的Y2XXX字段? – FFire

+0

@FFire。 。 。如果需要,您可以繼續添加子查詢 - 電子表格可以幫助構建查詢。 –