引用上图。
我有表 1,我想用 SQL 生成表 2。
第一年必须设置为值 10。后面的值将 10 乘以表 1 中该年和前几年的乘数。
例如:
- 对于 2002 年,该值为 10 * 2(2002 年乘数)* 1(2001 年乘数)= 20。
- 对于 2005 年,该值为 10 * 5 * 3 * 1 * 2 * 1(所有前一年的乘数)= 300。
我该怎么做呢?我将不胜感激任何帮助。
最佳答案
我的一位同事很久以前教我一个技巧,可以使用对数性质解决这类问题。
基本上你可以这样做:
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
关于mysql - SQL 乘以所有先前行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40245849/