在DATETIME字段按月分组 [英] GROUP BY month on DATETIME field

查看:543
本文介绍了在DATETIME字段按月分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mysql中有以下查询:

I have the following query in 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

我想获取每个月的书名计数,因此结果如下:

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?

推荐答案

您可以尝试吗?

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".

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

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

这篇关于在DATETIME字段按月分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆