- 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
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)
Advertisements