

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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)
- Related Questions & Answers
- Count multiple rows and display the result in different columns (and a single row) with MySQL
- How to select the sum of the column values with higher value in reach row with MySQL?
- Return value from a row if it is NOT NULL, else return the other row value in another column with MySQL
- MySQL query to select one specific row and another random row?
- Get total in the last row of MySQL result?
- Only display row with highest ID in MySQL
- Display sum in last row of table using MySQL?
- How to display the count from distinct records in the same row with MySQL?
- How to divide the row values by row sum in R matrix?
- How to divide the row values by row sum in R data frame?
- Show row with zero value after addition in MySQL?
- Sum values of a single row in MySQL?
- Display first selected row in MySQL?
- How to find specific row with a MySQL query?
- How to move the ResultSet cursor to the previous row in JDBC?
Advertisements