Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY month on DATETIME field

Tags:

sql

mysql

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?

like image 623
David542 Avatar asked Jan 07 '14 03:01

David542


2 Answers

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) 
like image 170
SirPhemmiey Avatar answered Sep 18 '22 05:09

SirPhemmiey


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 |
+---------------------+---------------------+
like image 22
Jason Heo Avatar answered Sep 18 '22 05:09

Jason Heo