How to do a sum of previous row value with the current row and display the result in another row with MySQL cross join?


Let us first create a table −

mysql> create table DemoTable(Value int);
Query OK, 0 rows affected (1.79 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(50);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.68 sec)
mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
| 50    |
| 20    |
| 30    |
+-------+
3 rows in set (0.00 sec)

Here is the query to do a sum of previous rows in MySQL a sum of previous rows −

mysql> select t.Value,
   (@s := @s + t.Value) as Number
   from DemoTable t cross join
      (select @s := 0) p
   order by t.Value;

This will produce the following output −

+-------+--------+
| Value | Number |
+-------+--------+
| 20    | 20     |
| 30    | 50     |
| 50    | 100    |
+-------+--------+
3 rows in set (0.07 sec)

Updated on: 03-Sep-2019

891 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements