How to sum the values in the table by month with MySQL?

MySQLMySQLi Database

For this, use EXTRACT(), that would allow you to extract specific month records. For example, to add all the prices in January (irrespective of the year).

Let us first create a −

mysql> create table DemoTable1415
   -> (
   -> ProductPurchaseDate date,
   -> ProductPrice int
   -> );
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1415 values('2019-01-12',560);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1415 values('2018-01-14',1060);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1415 values('2017-03-21',780);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1415 values('2016-09-01',800);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1415 values('2019-01-14',100);
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select −

mysql> select * from DemoTable1415;

This will produce the following output −

+---------------------+--------------+
| ProductPurchaseDate | ProductPrice |
+---------------------+--------------+
| 2019-01-12          |          560 |
| 2018-01-14          |         1060 |
| 2017-03-21          |          780 |
| 2016-09-01          |          800 |
| 2019-01-14          |          100 |
+---------------------+--------------+
5 rows in set (0.00 sec)

Following is the query to sum the values in the table by month −

mysql> select extract(MONTH from ProductPurchaseDate) as month,sum(ProductPrice) as total_value from DemoTable1415
   -> group by month;

This will produce the following output −

+-------+-------------+
| month | total_value |
+-------+-------------+
|     1 |        1720 |
|     3 |         780 |
|     9 |         800 |
+-------+-------------+
3 rows in set (0.00 sec)
raja
Published on 12-Nov-2019 05:19:13
Advertisements