简体   繁体   English

仅按月份和年份分组日期

[英]Group dates by only month and year

Assuming I have a table like the following: 假设我有一个如下表:

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

Is it possible to make some sql query such that I get a grouping of all the dates by month and year? 是否可以进行一些sql查询,以便按月和年对所有日期进行分组? Is there some possibility that I could get a sorted result of: 我是否有可能得到以下排序结果:

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

I know you can GROUP BY duedate, but that only groups those with the same month, day, and year instead of just month and year. 我知道您可以GROUP BY截止日期,但是那只能将那些具有相同月份,日期和年份的分组,而不只是月份和年份。

Would it be then possible to even further group it such that it factors in "assignment" to obtain a resulting table of 那么是否有可能进一步对其进行分组,以使其将“赋值”作为因素来获得结果表。

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

Use the string functions YEAR and MONTH . 使用字符串函数YEARMONTH

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

Use MONTHNAME or DATE_FORMAT to get the name of the month. 使用MONTHNAMEDATE_FORMAT来获取月份的名称。

You can use this query. 您可以使用此查询。

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

try this 尝试这个

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

DEMO HERE 此处演示

will output this: 将输出以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM