Add records from corresponding duplicate values in another column with MySQL

MySQLMySQLi Database

For this, you can use the aggregate function SUM() along with the GROUP BY clause. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Name varchar(20),
   -> Value int
   -> );
Query OK, 0 rows affected (2.08 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris',50);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('David',90);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Chris',60);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Bob',100);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('David',80);
Query OK, 1 row affected (0.21 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+-------+-------+
| Name  | Value |
+-------+-------+
| Chris | 50    |
| David | 90    |
| Chris | 60    |
| Bob   | 100   |
| David | 80    |
+-------+-------+
5 rows in set (0.00 sec)

Following is the query to add records from duplicate values in another column −

mysql> select Name,sum(Value) as GrandTotal from DemoTable group by Name;

This will produce the following output −

+-------+------------+
| Name  | GrandTotal |
+-------+------------+
| Chris |        110 |
| David |        170 |
| Bob   |        100 |
+-------+------------+
3 rows in set (0.03 sec)
raja
Published on 17-Dec-2019 10:28:12
Advertisements