To create a cumulative sum column in MySQL, you need to create a variable and set to value to 0. Cumulative sum increments the next value step by step with current value.
Firstly, you need to create a variable with the help of SET. The syntax is as follows −
set @anyVariableName:= 0;
The syntax to create a cumulative sum column in MySQL is as follows −
select yourColumnName1,yourColumnName2,........N,(@anyVariableName := @anyVariableName + yourColumnName2) as anyVariableName from yourTableName order by yourColumnName1;
To understand the above concept, let us create a table. The following is the query to create a table −
mysql> create table CumulativeSumDemo −> ( −> BookId int, −> BookPrice int −> ); Query OK, 0 rows affected (0.67 sec)
Insert some records in the table with the help of select statement. The query to insert record is as follows −
mysql> insert into CumulativeSumDemo values(101,400); Query OK, 1 row affected (0.15 sec) mysql> insert into CumulativeSumDemo values(102,500); Query OK, 1 row affected (0.16 sec) mysql> insert into CumulativeSumDemo values(103,600); Query OK, 1 row affected (0.16 sec) mysql> insert into CumulativeSumDemo values(104,1000); Query OK, 1 row affected (0.18 sec)
Display all records which I have inserted with the help of insert command. The query is as follows −
mysql> select *from CumulativeSumDemo;
The following is the output −
+--------+-----------+ | BookId | BookPrice | +--------+-----------+ | 101 | 400 | | 102 | 500 | | 103 | 600 | | 104 | 1000 | +--------+-----------+ 4 rows in set (0.00 sec)
To add cumulative sum column, first you need to create a variable. The query is as follows −
mysql> set @CumulativeSum := 0; Query OK, 0 rows affected (0.00 sec)
Implement the above syntax discussed in the beginning to add a cumulative sum column. The query is as follows −
mysql> select BookId,BookPrice,(@CumulativeSum := @CumulativeSum + BookPrice) as CumSum −> from CumulativeSumDemo order by BookId;
The following is the output. Here the cumulative sum column is also visible −
+--------+-----------+--------+ | BookId | BookPrice | CumSum | +--------+-----------+--------+ | 101 | 400 | 400 | | 102 | 500 | 900 | | 103 | 600 | 1500 | | 104 | 1000 | 2500 | +--------+-----------+--------+ 4 rows in set (0.00 sec)