1

我需要在 Ruby on Rails 中运行 group_by 查询,但我首先想在运行查询之前将 created_at 列中的所有记录调整一定的小时数。因此,例如,为 created_at 字段中的每条记录添加 9 小时,然后按日期分组。

类似于以下内容(这是不正确的):

 @foo = Bar.group("date(created_at + 9.hours)").count

我怎样才能在 Rails 中做到这一点?

4

1 回答 1

2

PostgreSQL 对操作日期和时间有很好的支持(参见日期/时间函数和运算符)。您可以将 '9 hours' 表示为 a interval,将其添加到 a timestamp,然后转换为 a date

=> select (now()::timestamp + '9 hours'::interval)::date;
    date    
------------
 2012-09-22
(1 row)

这最终与您的原始伪代码惊人地相似:

@foo = Bar.group("date(created_at + '9 hours'::interval)").count
于 2012-09-22T00:37:39.520 回答