您可以借助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 −> );
使用以下查询在表中插入记录-
mysql> insert into GroupMonthAndYearDemo values(now()); mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval 2 year)); mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval -2 year)); mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval 1 year)); mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval -1 year));
在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)