 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
MySQL query to get sum of each column where every column has same number of values?
You can use aggregate function SUM() for this. Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstValue int, SecondValue int, ThirdValue int ); Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(10,20,30); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(60,50,40); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(80,90,100); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(FirstValue,SecondValue,ThirdValue) values(20,10,0); Query OK, 1 row affected (0.23 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+------------+-------------+------------+ | Id | FirstValue | SecondValue | ThirdValue | +----+------------+-------------+------------+ | 1 | 10 | 20 | 30 | | 2 | 60 | 50 | 40 | | 3 | 80 | 90 | 100 | | 4 | 20 | 10 | 0 | +----+------------+-------------+------------+ 4 rows in set (0.00 sec)
Here is the query to get the sum of each column where every column has same count of values −
mysql> select sum(FirstValue),sum(SecondValue),sum(ThirdValue) from DemoTable;
This will produce the following output −
+-----------------+------------------+-----------------+ | sum(FirstValue) | sum(SecondValue) | sum(ThirdValue) | +-----------------+------------------+-----------------+ | 170 | 170 | 170 | +-----------------+------------------+-----------------+ 1 row in set (0.00 sec)
Advertisements
 