GROUP BY month on DATETIME field

2020-03-02 02:04发布

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

标签: mysql sql
5条回答
Viruses.
2楼-- · 2020-03-02 02:11
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 :)

查看更多
戒情不戒烟
3楼-- · 2020-03-02 02:16

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

SELECT Count(*), Date(timestamp) FROM title GROUP BY YEAR(timestamp), Month(timestamp) 
查看更多
够拽才男人
4楼-- · 2020-03-02 02:24

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.

mysql> SELECT MONTH('2013-01-01'), MONTH('2014-01-01');
+---------------------+---------------------+
| MONTH('2013-01-01') | MONTH('2014-01-01') |
+---------------------+---------------------+
|                   1 |                   1 |
+---------------------+---------------------+
查看更多
神经病院院长
5楼-- · 2020-03-02 02:25
select count(*), date(timestamp) from title group by MONTHNAME(timestamp)
查看更多
姐就是有狂的资本
6楼-- · 2020-03-02 02:33
select 
       count(*) as Count,
       MONTH(timestamp)+"-"+YEAR(timestamp) as Month 
from 
       title 
GROUP BY 
        MONTH(tumestamp);
查看更多
登录 后发表回答