MySQL DATETIME 字段上的 GROUP BY 月份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20963503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:46:30  来源:igfitidea点击:

GROUP BY month on DATETIME field

mysqlsql

提问by David542

I have the following query in mysql:

我在 mysql 中有以下查询:

SELECT title, 
       added_on 
FROM   title 

The results looks like this:

结果如下所示:

Somos T?o Jovens                        2013-10-10 16:54:10
Moulin Rouge - Amor em Vermelho         2013-10-10 16:55:03
Rocky Horror Picture Show (Legendado)   2013-10-10 16:58:30
The X-Files: I Want to Believe          2013-10-10 22:39:11

I would like to get the count for the titles in each month, so the result would look like this:

我想获得每个月的标题计数,因此结果如下所示:

Count               Month
42                  2013-10-01
20                  3013-09-01

The closest I can think of to get this is:

我能想到的最接近的是:

SELECT Count(*), 
       Date(timestamp) 
FROM   title 
GROUP  BY Date(timestamp) 

But this is only grouping by the day, and not the month. How would I group by the month here?

但这只是按天分组,而不是按月分组。我将如何按月份分组?

回答by Jason Heo

Could you try this?

你能试试这个吗?

select count(*), DATE_FORMAT(timestamp, "%Y-%m-01")
from title
group by DATE_FORMAT(timestamp, "%Y-%m-01")

Please, note that MONTH()can't differentiate '2013-01-01' and '2014-01-01' as follows.

请注意,MONTH()不能如下区分“2013-01-01”和“2014-01-01”。

mysql> SELECT MONTH('2013-01-01'), MONTH('2014-01-01');
+---------------------+---------------------+
| MONTH('2013-01-01') | MONTH('2014-01-01') |
+---------------------+---------------------+
|                   1 |                   1 |
+---------------------+---------------------+

回答by NewInTheBusiness

SELECT Count(*), 
       Date(timestamp) 
FROM   title 
GROUP  BY Month(timestamp) 

Edit: And obviously if it matters to display the 1st day of the month in the results, you do the DATE_FORMAT(timestamp, "%Y-%m-01")thing mentioned in some other answers :)

编辑:很明显,如果在结果中显示当月的第一天很重要,你会做DATE_FORMAT(timestamp, "%Y-%m-01")一些其他答案中提到的事情:)

回答by The Hungry Dictator

select 
       count(*) as Count,
       MONTH(timestamp)+"-"+YEAR(timestamp) as Month 
from 
       title 
GROUP BY 
        MONTH(tumestamp);

回答by SirPhemmiey

The best bet is to group it by YEAR and then by MONTH. See below

最好的办法是按 YEAR 分组,然后按 MONTH 分组。见下文

SELECT Count(*), Date(timestamp) FROM title GROUP BY YEAR(timestamp), Month(timestamp) 

回答by Surabhil Sergy

select count(*), date(timestamp) from title group by MONTHNAME(timestamp)