
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
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 Articles
- 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
- 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?
- MySQL query to select one specific row and another random row?\n
- Get total in the last row of MySQL result?
- Show row with zero value after addition in MySQL?
- How to divide the row values by row sum in R matrix?
- How to find specific row with a MySQL query?
- How to count number of NULLs in a row with MySQL?
- Display first selected row in MySQL?
- How to select first and last data row from a MySQL result?
- How to divide the row values by row sum in R data frame?

Advertisements