MySQL query to get sum of each column where every column has same number of values?

MySQLMySQLi Database

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)
raja
Published on 29-Apr-2019 11:19:28
Advertisements