- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements