小编典典

在DATETIME字段按月分组

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)

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


阅读 388

收藏
2021-03-17

共1个答案

小编典典

你可以试试这个吗?

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 |
+---------------------+---------------------+
2021-03-17