MySQL SELECT to sum a column value with previous value



For this, you can use a session variable. Let us first create a table −

mysql> create table DemoTable809(Price int); Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable809 values(40); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable809 values(50); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable809 values(60); Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable809;

This will produce the following output −

+-------+ | Price | +-------+ |    40 | |    50 | |    60 | +-------+ 3 rows in set (0.00 sec)

Following is the query to sum a column value with a previous value −

mysql> select @currentSum:=@currentSum+Price from DemoTable809;

This will produce the following output −

+--------------------------------+ | @currentSum:=@currentSum+Price | +--------------------------------+ |                             40 | | 90 | | 150 | +--------------------------------+ 3 rows in set (0.00 sec)
Updated on: 2019-09-03T10:51:46+05:30

875 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements