【问题标题】:How to group by day and year in Active Record in Rails3如何在 Rails3 的 Active Record 中按日期和年份分组
【发布时间】:2013-05-30 17:31:14
【问题描述】:

我正在尝试在 rails 3 中重新创建以下 mysql 查询

 select count(id), year(created_at), month(created_at) from table where published_state = 'published' group by year(created_at), month(created_at);

我尝试过类似的方法:

results = Table.select('count(id), year(created_at), month(created_at)').where('published_state LIKE ?', 'published').group('year(created_at), month(created_at)')

但它没有返回我想要的。

我只是得到这个作为回报

[#<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >,
 #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >]

我怎样才能做到这一点?

谢谢!

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-3 activerecord group-by


    【解决方案1】:

    试试这个:

    Table.where(:published_state => 'published').
      group('year(created_at)').group('month(created_at)').count(:id)
    

    结果的格式不是我所期望的(它是一个带有数组键的散列,如 [year, month] 和计数值)但也许它会满足您的目的?

    【讨论】:

    • 是的,实际上,有一种方法可以在每个结果中包含 id 吗?
    【解决方案2】:

    如果您使用的是 PostgreSQL,您还可以使用 date_trunc 函数(为了便于阅读而拆分行,但可能不适用于真正的 Ruby):

    Table.select('count(id), date_trunc('month', created_at) as month')
      .where('published_state LIKE ?', 'published').group('month')
    

    基本上,它会截断或切断不再重要的日期部分。例如,如果您选择“月”,它仍然会保留带有月份的年份,但不会保留日期和时间。

    我可能也会这样订购:

    Table.select('count(id), date_trunc('month', created_at) as month')
      .where('published_state LIKE ?', 'published').group('month')
      .order('month' DESC)
      .limit(24)
    

    阅读更多文档here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 2018-04-13
      相关资源
      最近更新 更多