【问题标题】:mysql calculate using combination of sum and product formulamysql 使用 sum 和 product 公式的组合计算
【发布时间】:2021-02-26 09:36:22
【问题描述】:

我在 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

【问题讨论】:

  • 使用递归 CTE。
  • 您的问题假设表中有排序。但是,表格是无序的。目前尚不清楚订单是什么。样本数据和期望的结果也会使问题更加清晰——并且更有可能得到回答。提示:字符串上的算术没有意义。
  • @GordonLinoff 感谢您的评论,提供示例数据和输出。

标签: mysql sql cumulative-sum


【解决方案1】:

您可以使用递归 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;

查看演示here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 2022-01-19
    • 2018-10-10
    相关资源
    最近更新 更多