
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Get the Sum of Columns for Duplicate Records in MySQL
For this, use GROUP BY clause along with aggregate function SUM(). Let us first create a table −
mysql> create table DemoTable( Name varchar(100), Score int ); Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Adam',50); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Bob',80); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Adam',70); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Adam',10); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Carol',98); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('Bob',10); Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+-------+ | Name | Score | +-------+-------+ | Adam | 50 | | Bob | 80 | | Adam | 70 | | Adam | 10 | | Carol | 98 | | Bob | 10 | +-------+-------+ 6 rows in set (0.00 sec)
Following is the query to get the sum of columns for duplicate records in MySQL −
mysql> select Name,sum(Score) from DemoTable group by Name;
This will produce the following output −
+-------+------------+ | Name | sum(Score) | +-------+------------+ | Adam | 130 | | Bob | 90 | | Carol | 98 | +-------+------------+ 3 rows in set (0.00 sec)
Advertisements