SUM corresponding duplicate records in MySQL

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> StudentName varchar(20),
   -> StudentMarks int
   -> );
Query OK, 0 rows affected (0.68 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris',50);
Query OK, 1 row affected (0.61 sec)
mysql> insert into DemoTable values('David',70);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('Chris',80);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('David',90);
Query OK, 1 row affected (0.24 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| Chris       |           50 |
| David       |           70 |
| Chris       |           80 |
| David       |           90 |
+-------------+--------------+
4 rows in set (0.00 sec)

Here is the query to sum corresponding duplicate records i.e. the marks of students −

mysql> select StudentName,sum(StudentMarks) from DemoTable group by StudentName;

This will produce the following output −

+-------------+-------------------+
| StudentName | sum(StudentMarks) |
+-------------+-------------------+
| Chris       |               130 |
| David       |               160 |
+-------------+-------------------+
2 rows in set (0.00 sec)
raja
Published on 18-Dec-2019 10:48:14
Advertisements