sql - 更新两列排序的累积总和

标签 sql sqlite cumulative-sum

给定表:

id   date count cumulative_sum
1    2    100                  
2    1    50
3    1    10
4    2    5


如何更新cumulative_sumdate排序的行中的id

结果应为:

id   date count cumulative_sum
2    1    50    50
3    1    10    60
1    2    100   160
4    2    5     165


当我插入或更新一行时,是否还可以仅更新那些需要重新计算的行?

最佳答案

您可以使用此:

update your_table
set
  cumulative_sum = (select sum(c)
                    from your_table t2
                    where
                      t2.date<your_table.date
                      or (t2.date=your_table.date
                          and t2.id<=your_table.id));


子查询对计数的累积总和进行计数,该总和是日期小于当前行日期的所有值的总和,或者日期=当前行的日期且id为<的所有值的总和。

您还可以提出以下条件:

where cumulative_sum is null


仅在没有值的情况下才更新行。如果插入表中的所有ID和日期始终按升序排列,则此方法有效。

关于sql - 更新两列排序的累积总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14031864/

相关文章:

php - 更新大型 MySQL 表

ios - 由于文档文件夹中的 sqlite 数据库被苹果拒绝

ios - [__NSCFString objectForKey :]: unrecognized selector sent to instance 0xa6a2750

matlab - 如何在 MATLAB 中执行此累积和?

python - 与 windows 相比,ubuntu 中 python 程序的运行时间非常小。为什么?

mysql - 如何实现 "complex"INSERT 查询来检索调用其他查询的值?

sql - 我可以在不引用另一个表的情况下对列进行约束吗?

sql - 如何在没有安装 dev 库的情况下在 C 中使用 sqlite3?

powerbi - 如何计算 DAX 中的累计总数和百分比?

php - MySql 中的按计数分组(用户和组)