I have a table of the form
Category Time Qty
A 1 20
B 2 3
A 3 43
A 4 20
B 5 25
I need a running total to be calculated by category in MySQL. The result would look something like this:
Category Time Qty Cat.Total
A 1 20 20
B 2 3 3
A 3 43 63
A 4 20 83
B 5 25 28
Any idea how I could do this efficiently in MySQL? I have searched far and wide, but all I can find is info on how to insert one single running total in MySQL. I wonder if there's any way to use GROUP BY or a similar construct to achieve this.
You could calculate the sum in a subquery:
Trading readability for speed, you can use a MySQL variable to hold the running sum:
The ordering is required for this construct to work; if you need a different order, wrap the query in a subquery: