rails 3按日期分组日期时间列

时间:2010-10-28 12:55:46

标签: datetime ruby-on-rails-3

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

我如何按日期分组? “start_at”列是日期时间列

3 个答案:

答案 0 :(得分:36)

这应该有用(轨道3):

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

编辑:如果你正在使用PostgreSQL,那么查询应该是

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

或者你会收到错误

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

基于

Graphing new users by date in a Rails app using Seer

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

答案 1 :(得分:8)

我为此创造了一个宝石。 https://github.com/ankane/groupdate

Foo.group_by_day(:created_at).count

您甚至可以指定时区。

Foo.group_by_day(:created_at, time_zone: "Pacific Time (US & Canada)").count

答案 2 :(得分:0)

如果您管理不同的时区,这是解决此问题的另一种方法。想法是添加或减去您的时区的小时数:

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