仅按月和年份分组日期

时间:2013-02-21 22:04:54

标签: mysql

假设我有一个如下表:

id | assignment | duedate
1  | Math       | 2012-01-01
2  | History    | 2012-02-02
3  | Science    | 2012-01-01
4  | Government | 2012-02-01
5  | Government | 2013-01-13
6  | History    | 2013-03-13

是否可以进行一些SQL查询,以便按月和按年分组所有日期?我是否有可能获得以下的排序结果:

duedatemonth  | count 
January 2012  | 2
Feburary 2012 | 2
January 2013  | 1
March 2013    | 1

我知道您可以使用GROUP BY duedate,但这只会将那些月,日和年分组,而不仅仅是月和年。

是否有可能进一步对其进行分组,使其在“赋值”中考虑因素以获得结果表

id | duedatemonth  | count 
1  | January 2012  | 2
3  | January 2012  | 2
2  | Feburary 2012 | 2
4  | Feburary 2012 | 2
5  | January 2013  | 1
6  | March 2013    | 1

3 个答案:

答案 0 :(得分:0)

使用字符串函数YEARMONTH

SELECT YEAR(duedate), MONTH(duedate), COUNT(*)
FROM sparkles
GROUP BY YEAR(duedate), MONTH(duedate)

使用MONTHNAMEDATE_FORMAT获取月份名称。

答案 1 :(得分:0)

您可以使用此查询。

SELECT DATE_FORMAT(duedate, '%M %Y') duedatemonth, COUNT(1) `count`
FROM Tbl
GROUP BY DATE_FORMAT(duedate, '%M %Y')

答案 2 :(得分:0)

试试这个

    SELECT DATE_FORMAT(duedate,'%M %Y')  duedatemonth, COUNT(*) count
    FROM Table1
   GROUP BY year(duedate), MONTH(duedate)

DEMO HERE

将输出:

   DUEDATEMONTH     COUNT
   January 2012     2
  February 2012     2
   January 2013     1
     March 2013     1