In Ruby on Rails, created_at and updated_at columns are MySQL timestamp columns. GROUP BY is pretty useless on a timestamp column, unless you are trying to group rows that were added at the same second. I needed to group by just the date, so in order to do this I had to manipulate the timestamp with a MySQL operator. Using the DATE_FORMAT operator, you can easily group the timestamp column using any format you want. For my example, I needed to group rows that were added on the same day. Here is my query:
select count(*), DATE_FORMAT(created_at,"%Y-%m-%d") as created_day FROM widgets GROUP BY created_day
This query will give you something like this:
count(*) | created_day 126 | 2010-04-12 168 | 2010-04-13 169 | 2010-04-14 189 | 2010-04-15 187 | 2010-04-16 13 | 2010-04-17
Group by month:
select count(*), DATE_FORMAT(created_at,"%Y-%m") as created_month FROM widgets GROUP BY created_month
Group by year:
select count(*), DATE_FORMAT(created_at,"%Y") as created_year FROM widgets GROUP BY created_year




#1 by Himanshu on July 23, 2011 - 10:06 pm
Quote
Life Saver.
#2 by bjj4me on October 14, 2011 - 10:50 pm
Quote
Great Post
Pingback: MySQL group by day, month or year using a timestamp column | prosoxi.com
Trackback: mobila ucraina
#3 by Forsvunnet on February 13, 2012 - 3:32 pm
Quote
I absolutely adore you for posting this, and in so saying I’d like to add that date_format also works great for selecting entries from a specific month. eg: $sql =”SELECT count(*) FROM entries WHERE DATE_FORMAT(time,’%Y-%m’) = ‘”. date(‘Y-m’) .”‘”;
#4 by Reuben Waitara on January 11, 2013 - 2:33 am
Quote
I simply LOVE YOU dude, thanx alot, u r my life saviour
#5 by Akam on January 11, 2013 - 12:53 pm
Quote
This query can be used for daily total, it show count(*) for each day.
You can also change group by to show monthly count(*).
select
count(*) all,
year(created_at) as year,
month(created_at) as month,
day(created_at) as day
FROM widgets
GROUP BY year(created_at), month(created_at), as day
ORDER by crated_at asc
#6 by Emin on January 20, 2013 - 11:44 am
Quote
Thanks!
#7 by sachin on March 6, 2013 - 4:59 pm
Quote
Thank a lot friend. Worked for me and saved a lots of my time