Group month and year in MySQL?

MySQLMySQLi Database

You can group month and year with the help of function DATE_FORMAT() in MySQL. The GROUP BY clause is also used.

The syntax is as follows −

SELECT DATE_FORMAT(yourColumnName, '%m-%Y') from yourTableName
GROUP BY MONTH(yourColumnName), YEAR(yourColumnName)DESC;

To understand the above concept, let us create a table. The following is the query to create a table −

mysql> create table GroupMonthAndYearDemo
   −> (
   −> DueDate datetime
   −> );
Query OK, 0 rows affected (1.49 sec)

Insert records in the table using the following query −

mysql> insert into GroupMonthAndYearDemo values(now());
Query OK, 1 row affected (0.11 sec)

mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval 2 year));
Query OK, 1 row affected (0.12 sec)

mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval -2 year));
Query OK, 1 row affected (0.10 sec)

mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval 1 year));
Query OK, 1 row affected (0.16 sec)

mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval -1 year));
Query OK, 1 row affected (0.14 sec)

Display all records from the table with the help of select statement. The query is as follows −

mysql> select *from GroupMonthAndYearDemo;

The following is the output −

+---------------------+
| DueDate             |
+---------------------+
| 2018-12-06 13:12:34 |
| 2020-12-06 13:12:59 |
| 2016-12-06 13:13:08 |
| 2019-12-06 13:13:14 |
| 2017-12-06 13:13:19 |
+---------------------+
5 rows in set (0.00 sec)

The query to group by month and year is as follows −

mysql> select DATE_FORMAT(DueDate, '%m-%Y') from GroupMonthAndYearDemo 
   −> GROUP BY MONTH(DueDate) , YEAR(DueDate)DESC;

The following is the output displaying month and year grouped by using GROUP BY −

+-------------------------------+
| DATE_FORMAT(DueDate, '%m-%Y') |
+-------------------------------+
| 12-2020                       |
| 12-2019                       |
| 12-2018                       |
| 12-2017                       |
| 12-2016                       |
+-------------------------------+
5 rows in set, 2 warnings (0.00 sec)
raja
Published on 11-Jan-2019 12:16:53
Advertisements