Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3 group by date a datetime column

Tags:

Foo.group(:start_at).count(:id) 

How I can group this by date ? the "start_at" column is an datetime column

like image 979
astropanic Avatar asked Oct 28 '10 12:10

astropanic


2 Answers

This should work (rails 3):

Foo.order(:start_at).group("DATE(start_at)").count 

edit: if you're using PostgreSQL, the query should be

Foo.order("DATE(start_at)").group("DATE(start_at)").count 

or you'll get an error

("PGError: ERROR:  column "foos.start_at" must appear in the GROUP BY clause or be used in an aggregate function") 

Based on

Graphing new users by date in a Rails app using Seer

and

http://www.pastbedti.me/2009/11/grouping-a-timestamp-field-by-date-in-ruby-on-rails-postgresql/

like image 126
David Sulc Avatar answered Sep 16 '22 15:09

David Sulc


I created a gem for this. https://github.com/ankane/groupdate

Foo.group_by_day(:created_at).count 

You can even specify a time zone.

Foo.group_by_day(:created_at, time_zone: "Pacific Time (US & Canada)").count 
like image 39
Andrew Kane Avatar answered Sep 20 '22 15:09

Andrew Kane