DATETIME字段上的GROUP BY月份

时间:2014-01-07 03:42:14

标签: mysql sql

我在mysql中有以下查询:

SELECT title, 
       added_on 
FROM   title 

结果如下:

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

我想得到每个月的标题数,所以结果看起来像这样:

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

我能想到的最接近的是:

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

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

5 个答案:

答案 0 :(得分:31)

你可以尝试一下吗?

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

请注意,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 |
+---------------------+---------------------+

答案 1 :(得分:4)

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

编辑:显然,如果在结果中显示该月的第一天很重要,那么您可以执行其他答案中提到的DATE_FORMAT(timestamp, "%Y-%m-01")事项。

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

最好的选择是按年份分组,然后按月份分组。见下文

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