简体   繁体   中英

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. I've been trying lots of variations using SUM(CASE WHEN... and other groupings to no avail.

If your id field is sequential and growing then a correlated subquery is one way:

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):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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