mysql - 如何将小计添加到 MySQL 中的表中?

标签 mysql sum case

假设我的表格如下所示:

id    count    sub_total
1     10       NULL
2     15       NULL
3     10       NULL
4     25       NULL

我怎样才能将此表更新为如下所示?

id    count    sub_total
1     10       10
2     15       25
3     10       35
4     25       60 

我可以在应用层很容易地做到这一点。但我想学习如何在 MySQL 中做到这一点。我一直在尝试使用 SUM(CASE WHEN... 和其他分组进行多种变体,但均无济于事。

最佳答案

如果您的 id 字段是连续的并且在增长,那么相关子查询是一种方式:

select *, (select sum(count) from t where t.id <= t1.id) 
from t t1

或作为连接:

select t1.id, t1.count, sum(t2.count)
from t t1
join t t2 on t2.id <= t1.id
group by t1.id, t1.count
order by t1.id

要更新您的表(假设 sub_total 列已经存在):

update t 
join (
  select t1.id, sum(t2.count) st
  from t t1
  join t t2 on t2.id <= t1.id
  group by t1.id
) t3 on t.id = t3.id
set t.sub_total = t3.st;

Sample SQL Fiddle显示更新。

关于mysql - 如何将小计添加到 MySQL 中的表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31991804/

相关文章:

PHP If 语句在过滤 SQL 表时不起作用

mysql - Pandas Dataframe - Mysql 从表中选择 <A 列来自 Dataframe> 中的条件

SQL Max(something,0) 类型解决方案

对 p 和 q 之间(包括)之间的数字求和的算法

mysql - MySQL WHERE 子句中的 CASE 或 COALESCE 性能

android - 是否可以在 flutter 应用程序中为 android 应用程序创建一个 mySQL 数据库,并将该连接用作 flutter 本身的数据库服务器?

c# - Dapper Multi Mapping 上的某些值返回 null

mysql - 更好的 SQL 来汇总多个表中的相同列?

php - 为什么即使没有找到匹配项,switch 语句也会执行 case block ?

mysql - 选择案例 * 何时