- 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
Sum up values in a single MySQL column in a specific way?
Use aggregate function SUM() along with OVER. Let us first create a table −
mysql> create table DemoTable ( CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY, CustomerValue int ); Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(CustomerValue) values(10); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(CustomerValue) values(20); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(CustomerValue) values(30); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(CustomerValue) values(40); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+---------------+ | CustomerId | CustomerValue | +------------+---------------+ | 1 | 10 | | 2 | 20 | | 3 | 30 | | 4 | 40 | +------------+---------------+ 4 rows in set (0.00 sec)
Following is the query to sum up values in a single column in a specific way −
mysql> select CustomerId, SUM(CustomerValue) OVER (ORDER BY CustomerId) SpecificSum from DemoTable;
This will produce the following output −
+------------+-------------+ | CustomerId | SpecificSum | +------------+-------------+ | 1 | 10 | | 2 | 30 | | 3 | 60 | | 4 | 100 | +------------+-------------+ 4 rows in set (0.00 sec)
Advertisements