MySQL query to find sum of fields with same column value?

MySQLMySQLi Database

Use GROUP BY clause for this. Let us first create a table −

mysql> create table sumOfFieldsDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ClientSerialNumber varchar(100),
   -> ClientCost int
   -> );
Query OK, 0 rows affected (0.50 sec)

Following is the query to insert some records in the table using insert command −

mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('1111',450);
Query OK, 1 row affected (0.16 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('2222',550);
Query OK, 1 row affected (0.15 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('3333',150);
Query OK, 1 row affected (0.64 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('3333',250);
Query OK, 1 row affected (0.12 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('2222',1000);
Query OK, 1 row affected (0.10 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('1111',1000);
Query OK, 1 row affected (0.16 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('1111',500);
Query OK, 1 row affected (0.17 sec)
mysql> insert into sumOfFieldsDemo(ClientSerialNumber,ClientCost) values('4444',100);
Query OK, 1 row affected (0.17 sec)

Following is the query to display all records from the table using select statement −

mysql> select * from sumOfFieldsDemo;

This will produce the following output −

+----+--------------------+------------+
| Id | ClientSerialNumber | ClientCost |
+----+--------------------+------------+
| 1  | 1111               | 450        |
| 2  | 2222               | 550        |
| 3  | 3333               | 150        |
| 4  | 3333               | 250        |
| 5  | 2222               | 1000       |
| 6  | 1111               | 1000       |
| 7  | 1111               | 500        |
| 8  | 4444               | 100        |
+----+--------------------+------------+
8 rows in set (0.00 sec)

Here is the query to find sum of fields with same column value −

mysql> select Id,ClientSerialNumber,SUM(ClientCost) AS TotalSum
   -> from sumOfFieldsDemo
   -> group by ClientSerialNumber;

This will produce the following output −

+----+--------------------+----------+
| Id | ClientSerialNumber | TotalSum |
+----+--------------------+----------+
| 1  | 1111               | 1950     |
| 2  | 2222               | 1550     |
| 3  | 3333               | 400      |
| 8  | 4444               | 100      |
+----+--------------------+----------+
4 rows in set (0.00 sec)
raja
Published on 16-Apr-2019 13:20:53
Advertisements