How to sum selected column values based on specific month records in MySQL?


Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   PurchaseDate date,
   SalePrice int
);
Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(PurchaseDate,SalePrice) values('2018-01-10',450);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(PurchaseDate,SalePrice) values('2019-12-25',1000);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(PurchaseDate,SalePrice) values('2016-12-02',5560);
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable(PurchaseDate,SalePrice) values('2015-02-20',4550);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(PurchaseDate,SalePrice) values('2015-12-11',4110);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------------+-----------+
| Id | PurchaseDate | SalePrice |
+----+--------------+-----------+
|  1 | 2018-01-10   |       450 |
|  2 | 2019-12-25   |      1000 |
|  3 | 2016-12-02   |      5560 |
|  4 | 2015-02-20   |      4550 |
|  5 | 2015-12-11   |      4110 |
+----+--------------+-----------+
5 rows in set (0.00 sec)

Following is the query to sum selected column values in MySQL based on a specific month. For example, here only the SalePrice has added for PurchaseDate in 12th month i.e. December −

mysql> select SUM(SalePrice) from DemoTable
   where month(PurchaseDate)=12;

The above adds records (SalePrice) for only the selected month i.e. 12th month December −

2019-12-25
2016-12-02
2015-12-11

This will produce the following output −

+----------------+
| SUM(SalePrice) |
| 10670          |
+----------------+
1 row in set (0.00 sec)

Updated on: 04-Oct-2019

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements