MySQL query to group by column and display the sum of similar values in another column


For this, use GROUP BY HAVING clause.

Let us first create a table −

mysql> create table DemoTable782 (
   Name varchar(100),
   Score int
);
Query OK, 0 rows affected (1.18 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable782 values('John',156);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable782 values('Carol',250);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable782 values('Bob',140);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable782 values('John',126);
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable782 values('John',140);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable782 values('Bob',280);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable782 values('Bob',250);
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable782 values('Carol',189);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable782 values('Carol',299);
Query OK, 1 row affected (0.21 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable782;

This will produce the following output -

+-------+-------+
| Name  | Score |
+-------+-------+
| John  | 156   |
| Carol | 250   |
| Bob   | 140   |
| John  | 126   |
| John  | 140   |
| Bob   | 280   |
| Bob   | 250   |
| Carol | 189   |
| Carol | 299   |
+-------+-------+
9 rows in set (0.00 sec)

Following is the query to group by column and display the sum of similar values −

mysql> select Name,SUM(Score) AS Total
   from DemoTable782
   group by Name
   HAVING Total > 500;

This will produce the following output -

+-------+-------+
| Name  | Total |
+-------+-------+
| Carol | 738   |
| Bob   | 670   |
+-------+-------+
2 rows in set (0.00 sec)

Updated on: 09-Sep-2019

384 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements