开发者

rails 3 group by date a datetime column

开发者 https://www.devze.com 2023-01-22 23:39 出处:网络
Foo.group(:start_at).count开发者_如何学C(:id) How I can group this by date ? the \"start_at\" column is an datetime columnThis should work (rails 3):
Foo.group(:start_at).count开发者_如何学C(:id)

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


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/


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


This is another way to solve this if you manage different time zones. The idea is to add or substract the hours of your timezone:

hours_diff = Time.zone.now.time_zone.utc_offset/(60*60) rescue 0
hours_diff = hours_diff.to_i
date_group = "DATE(form_answers.created_at)"
if hours_diff > 0
  date_group = "DATE(DATE_ADD(form_answers.created_at, INTERVAL #{hours_diff} HOUR ))"
elsif hours_diff < 0
  date_group = "DATE(DATE_SUB(form_answers.created_at, INTERVAL #{hours_diff.abs} HOUR ))"
end
Foo.group(date_group).count

0

精彩评论

暂无评论...
验证码 换一张
取 消