请参阅上图。
我有表1,我想用SQL生成表2。
第一年必须设置为值10.下面的值将乘以该年的乘数和表1中的前几年。
例如:
我该怎么做呢?我很感激任何帮助。
答案 0 :(得分:0)
我的一位同事很久以前教过我一个使用对数属性来解决这类问题的技巧。
基本上你可以这样做:
Exp(sum(ln(multiplier)))
在OP之后编辑让我意识到它不完整
要执行您需要的累积逻辑,您应该将此应用于自联接
select a.youryear, Exp(sum(ln(b.multiplier))) cumulative_mutiplier
from yourtable as a
join
yourtable as b on a.youryear>=b.youryear
group by a.youryear;
我已在rextester
上准备了一项测试 create table yourtable (
youryear integer,
multiplier integer
);
insert into yourtable(youryear,multiplier) values (2000,10);
insert into yourtable(youryear,multiplier) values (2001,1);
insert into yourtable(youryear,multiplier) values (2002,2);
insert into yourtable(youryear,multiplier) values (2003,1);
insert into yourtable(youryear,multiplier) values (2004,3);
insert into yourtable(youryear,multiplier) values (2005,5);
select a.youryear, Exp(sum(ln(b.multiplier))) cumulative_mutiplier
from yourtable as a
join
yourtable as b on a.youryear>=b.youryear
group by a.youryear;
结果是:
youryear cumulative_mutiplier
1 2000 10
2 2001 10
3 2002 20
4 2003 20
5 2004 60
6 2005 300
答案 1 :(得分:0)
select year
,x
,@result := @result*coalesce(x,10) as result
from table1,(select @result:=1) i
order by year
;
# year, x, result
2000, , 10
2001, 1, 10
2002, 2, 20
2003, 1, 20
2004, 3, 60
2005, 5, 300