ActiveRecord与日期相关的查询; MySQL与PostgreSQL

时间:2011-11-28 22:10:15

标签: mysql ruby-on-rails postgresql activerecord

我有一个记录数据库,我希望选择最近几周的日期和按天分组以获取这些记录的每日计数。如果我手动编写MySQL查询,我会从以下内容开始:

SELECT COUNT( id ) AS count, DAY( created_at ) AS the_day
FROM  `results` 
GROUP BY the_day

如何使用ActiveRecord来抽象此查询,以便它也适用于PostgreSQL?所以,到目前为止,我有一个范围来选择上面的这个查询,但我不肯定这将适用于PostgreSQL:

  scope :recent, lambda {
    select(['id', 'COUNT(id) AS the_count', 'DAY(created_at) AS the_day'])
    .where(:created_at => 7.days.ago.utc...Time.now.utc)
    .order('the_day DESC')
    .group('the_day')
  }

1 个答案:

答案 0 :(得分:2)

SQL规范提供了一种与数据库无关的提取方法:EXTRACT(<unit> FROM <date>)