mysql使用和积公式组合计算
我在mysql中有一个表,其中的数据如下例所示mysql使用和积公式组合计算,mysql,sql,cumulative-sum,Mysql,Sql,Cumulative Sum,我在mysql中有一个表,其中的数据如下例所示 |ColA |ColB| |:---- |:------:| |A1 |B1 | |A2 |B2 | |A3 |B3 | |A4 |B4 | ... 我想使用以下公式计算Column colc: C1=A1*B1 C2=(C1+A2)*B2 C3=(C2+A3)*B3 C4=(C3+A4)*B4 可乐可乐可乐 15 2 6 42 37315 4 8 2552您可以使用递归CTE: with recursive to_r
|ColA |ColB|
|:---- |:------:|
|A1 |B1 |
|A2 |B2 |
|A3 |B3 |
|A4 |B4 |
...
我想使用以下公式计算Column colc:C1=A1*B1代码>
C2=(C1+A2)*B2代码>
C3=(C2+A3)*B3代码>
C4=(C3+A4)*B4代码>
可乐可乐可乐
15
2 6 42
37315
4 8 2552
您可以使用递归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;
请参阅演示。您可以使用递归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;
请参阅演示。使用递归CTE。您的问题假设表中有顺序。然而,表格是无序的。现在还不清楚订单是什么。样本数据和期望的结果也会使问题更加清楚——并且更有可能得到回答。提示:字符串上的算术没有意义。@GordonLinoff感谢您的评论,提供了示例数据和输出。请使用递归CTE。您的问题假设表中有顺序。然而,表格是无序的。现在还不清楚订单是什么。样本数据和期望的结果也会使问题更加清楚——并且更有可能得到回答。提示:字符串上的算术没有意义。@GordonLinoff感谢您的评论,提供了示例数据和输出。