简体   繁体   English

如何在MySQL中向表中添加小计?

[英]How can I add subtotal to table in MySQL?

Assume my table looks like the following: 假设我的表如下所示:

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

How can I update this table to look like the following? 如何更新此表格如下所示?

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

I can do this easy enough in the application layer. 我可以在应用程序层中轻松完成这项工作。 But I'd like to learn how to do it in MySQL. 但是我想学习如何在MySQL中做到这一点。 I've been trying lots of variations using SUM(CASE WHEN... and other groupings to no avail. 我一直在尝试使用SUM(CASE WHEN...大量变体SUM(CASE WHEN...和其他分组无济于事。

If your id field is sequential and growing then a correlated subquery is one way: 如果您的id字段是连续的并且正在增长,则相关子查询是一种方式:

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

or as a join: 或作为连接:

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

To update your table (assuming the column sub_total already exists): 要更新表(假设列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 showing the update. 示例SQL Fiddle显示更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM