To select accumulated column, let us first create a demo table. The query to create a table is as follows −
mysql> create table accumulatedDemo -> ( -> Value int -> ); Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into accumulatedDemo values(10); Query OK, 1 row affected (0.21 sec) mysql> insert into accumulatedDemo values(15); Query OK, 1 row affected (0.09 sec) mysql> insert into accumulatedDemo values(20); Query OK, 1 row affected (0.13 sec) mysql> insert into accumulatedDemo values(25); Query OK, 1 row affected (0.12 sec) mysql> insert into accumulatedDemo values(45); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from accumulatedDemo;
Here is the output −
+-------+ | Value | +-------+ | 10 | | 15 | | 20 | | 25 | | 45 | +-------+ 5 rows in set (0.00 sec)
The following is the query to select accumulated column −
mysql> set @previousSum =0; Query OK, 0 rows affected (0.00 sec) mysql> select Value, @previousSum: =@previousSum+ Value AS AccumulatedColumn from accumulatedDemo;
Here is the output −
+-------+-------------------+ | Value | AccumulatedColumn | +-------+-------------------+ | 10 | 10 | | 15 | 25 | | 20 | 45 | | 25 | 70 | | 45 | 115 | +-------+-------------------+ 5 rows in set (0.00 sec)