假设我的表格如下所示:
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/