In this post, I am populating a cumulative SUM column for a table of MySQL.
For example, If we are working with sales and inventory management domain, every day we require to calculate cumulative sum of different columns like: stock value, profit figure, expense figure.
Generally, we can use this kind of demonstration for report purpose only and if it is required to store, we can populate and store for permanent use.
Below is a small demonstration to calculate Cumulative SUM column.
First, create sample table with data:
CREATE TABLE tbl_SampleSum
INSERT INTO tbl_SampleSum
Populate cumulative SUM column using MySQL Variable:
SET @SumVariable := 0;
,(@SumVariable := @SumVariable + SumValue) AS CumulativeSum
ORDER BY ID;
Populate cumulative SUM column using MySQL Correlated query:
FROM tbl_SampleSum AS A
WHERE A.id <= B.id
) AS CumulativeSum
FROM tbl_SampleSum AS B
ORDER BY B.id
Please share your ideas and opinions about this topic with me, your contribution will add true value to this topic.
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.
If you like this post, then please share it with others.
Please follow dbrnd.com, I will share my experience towards the success of Database Research and Development Activity.
I put up a post every day, please keep reading and learning.
Discover Yourself, Happy Blogging !
Anvesh M. Patel.