有可能 "unpivot" table 和 SQL 吗?

Is it possible "unpivot" table with SQL?

我有一个 table:

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

需要逆轴旋转并进行一些计算 结果 table(年数据乘 "amount"):

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

可能吗?以及如何?

最简单的方法使用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;

还有其他方法(一些取决于数据库)。但是对于你的数据,这应该没问题。