在 MySQL 中对月份和年份进行分组?

mysqlmysqli database

您可以借助 MySQL 中的 DATE_FORMAT() 函数对月份和年份进行分组。GROUP BY 子句也可用于此。

语法如下 −

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

为了理解上述概念,让我们创建一个表。以下是创建表的查询 −

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

使用以下查询在表中插入记录 −

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)

使用 select 语句显示表中的所有记录。查询如下 −

mysql> select *from GroupMonthAndYearDemo;

以下是输出 −

+---------------------+
| 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)

按月份和年份分组的查询如下 −

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

以下是使用 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)

相关文章