How to Calculate a running total in MySQL?

In this post, we will discuss how to Calculate a running total in MySQL where we can create a user-defined variable that will be used for keeping track or record of the sum at every level and continue to add. And even we can use a subquery and a join also for the same. And here we will discuss both ways to achieve our desired output as per our choice with some examples of the same.


Calculate a Running Total

For doing it we have certain code to execute that we will be listed here for the same we go with implementing the same using a user-defined variable to keep a track of the sum and keep on adding the value each time in an additional column which we can insert just to implement.

SELECT date_column, amount_column, (@running_total := @running_total + amount_column) AS running_total
FROM my_table, (SELECT @running_total := 0) AS rt
ORDER BY date_column;

Replace ‘My table’ with the name of your table, ‘Date column’ ¬†with the name of the column that contains the dates, and ‘amount column with the name of the column that contains the values you want to sum.

This query uses a user-defined variable @running_total to keep track of the running total. The:= operator is used to assign the initial value of 0 to the @running_total variable.

The sum function is used to calculate the sum of the ‘Amount column’ for each row. The result of the sum is added to the @running_total variable, and the result is returned as the running total column in the query results.

The order by clause is used to sort the results by the date column in ascending order.

For the result of the above code, we have the output below where we can see how we have created an extra column as a running total to get the result stored as the total at every point of time where ever we want to know.

| date_ column | amount_ column | running_ total |
| 2022-01-01  | 100           | 100           |
| 2022-01-02  | 50            | 150           |
| 2022-01-03  | 75            | 225           |
| 2022-01-04  | 25            | 250           |
| 2022-01-05  | 125           | 375           |

It is some what same as finding the commutative values i a table where we keep on adding new values to the existing value where we have to add the new value to existing sum of all the values till that value.


To Learn More about Creating a Sum Column in MySQL visit: by point of the tutorial

To learn more about MySQL tutorials and the solutions to the problems along with concepts and tutorials of solutions list and learn visit: MySQL Tutorials And Problems.


Leave a Comment

%d bloggers like this: