首页 > 解决方案 > mysql 使用 sum 和 product 公式的组合计算

问题描述

我在 mysql 中有一个表,其中的数据看起来像这个例子。

|ColA |ColB|
|:---- |:------:|
|A1   |B1  |
|A2   |B2  |
|A3   |B3  |
|A4   |B4  |
...

我想使用以下公式计算列 colc:
C1 = A1*B1;
C2 = (C1+A2)*B2;
C3 = (C2+A3)*B3;
C4 = (C3+A4)*B4;
...

ColA ColB ColC
1 5 5
2 6 42
3 7 315
4 8 2552

标签: mysqlsqlcumulative-sum

解决方案


您可以使用递归 CTE:

with recursive to_r as (select row_number() over (order by t.ColA) r, t.* from test_table t), 
     cte as (
        select t.r, t.ColA*t.ColB p from to_r t where t.r = 1
        union all
        select c.r+1, t1.ColB*(t1.ColA+c.p) from cte c join to_r t1 on t1.r = c.r+1
        
)
select p from cte;

在此处查看演示。


推荐阅读