How to sum cells in a column if a condition is met in another column with MySQL?


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
   -> (
   -> EmployeeName varchar(20),
   -> JoiningDate date,
   -> Salary int
   -> );
Query OK, 0 rows affected (0.54 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('David','2019-11-02',400);
Query OK, 1 row affected (0.52 sec)
mysql> insert into DemoTable values('Robert','2018-11-25',100);
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable values('Bob','2019-12-14',600);
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('Carol','2019-11-03',300);
Query OK, 1 row affected (0.23 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+--------------+-------------+--------+
| EmployeeName | JoiningDate | Salary |
+--------------+-------------+--------+
| David        | 2019-11-02  |    400 |
| Robert       | 2018-11-25  |    100 |
| Bob          | 2019-12-14  |    600 |
| Carol        | 2019-11-03  |    300 |
+--------------+-------------+--------+
4 rows in set (0.00 sec)

Here is the query to sum cells in a column if a condition is met in another column −

mysql> select year(JoiningDate) as JoiningYear,
   -> month(JoiningDate) as JoiningMonth,
   -> sum(Salary) as Total,
   -> group_concat(EmployeeName) as Name
   -> from DemoTable
   -> group by JoiningYear,JoiningMonth;

This will produce the following output −

+-------------+--------------+-------+-------------+
| JoiningYear | JoiningMonth | Total | Name        |
+-------------+--------------+-------+-------------+
|        2018 |           11 |   100 | Robert      |
|        2019 |           11 |   700 | David,Carol |
|        2019 |           12 |   600 | Bob         |
+-------------+--------------+-------+-------------+
3 rows in set (0.04 sec)

Updated on: 28-Feb-2020

740 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements