mysql - 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
解决方案
您可以使用递归 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;
在此处查看演示。
推荐阅读
- visual-studio - Visual Studio 的 CentOS 8.1 服务器上的奇怪键映射
- node.js - Xpath:在 Devtools 中工作,但使用 document.evaluate() 返回空对象
- java - Android Studio 上的 Flutter - Intellisense 无法正常工作
- google-apis-explorer - 在 Apps 脚本中启动查询时响应太大而无法在 BigQuery 中返回
- botframework - TypeError:词汇表不包含 UNK 标记
- python - 如何在类方法装饰器的 self 参数中添加类型注释?
- java - 一致的崩溃 Android - 播放计费
- excel - 如何在电源查询中仅转置表的某些列?
- c# - 如何使用第三方程序、PowerShell 或 C# 监控 Microsoft Outlook 以确定加载时间和涉及的因素?
- sql-server - 防止保存需要在 SQL 中重新创建表的更改