我有一张桌子:
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
有可能吗?怎么样?
答案 0 :(得分: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;
还有其他方法(一些取决于数据库)。但是对于你的数据,这应该没问题。