【问题标题】:How to write a rails query that returns the count by Month?如何编写一个按月返回计数的rails查询?
【发布时间】:2012-05-15 20:54:47
【问题描述】:

采用标准 NewsFeed 模型 (id,user_id)

如何在 NewsFeed 模型中查询每个月的记录数,然后排除几个 user_id?

结果会产生:

Jan - 313
Feb - 3131
Mar - 44444
etc...

有没有一种简单的方法可以使用 rails 来完成这项工作,或者您是否需要为每个月编写一个查询?

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:

    在 Rails 4 中,这样做的方法是在模型上创建范围。

    class NewsFeed < ActiveRecord::Base
      scope :group_by_month,   -> { group("date_trunc('month', created_at) ") }
      scope :exclude_user_ids, -> (ids) { where("user_id is not in (?)",ids) }
    end
    

    然后你会这样称呼它:

    @counts = NewsFeed.exclude_user_ids(['1','2']).group_by_month.count
    

    这会给你:

    {2014-01-01 00:00:00 UTC=>313, 2014-02-01 00:00:00 UTC=>3131}
    

    然后你输出(haml):

    - @counts.each do |m|
      = "Month: #{m[0].strftime("%b")}, Count: #{m[1]}"
    

    这会导致:

    Month: Jan, Count: 313
    Month: Feb, Count: 3131
    

    【讨论】:

    • 由于范围和解释结果而在所选答案下首选
    【解决方案2】:

    活动记录中有计数和组语句可用 所以你可以做一些类似于

    NewsFeed.count(:group=>"date_trunc('month', created_at)",:conditions=>"user_id NOT IN (?)",[exluded_ids])
    

    【讨论】:

    • PG::Error: 错误:列“月”不存在
    • 我稍微改变了示例
    • 谢谢,但错误:ActiveRecord::StatementInvalid: PG::Error: ERROR: column "news_feeds.created_at" 必须出现在 GROUP BY 子句中或在聚合函数中使用
    • 如果你把这两个答案结合起来,你应该得到那里
    【解决方案3】:

    也许这会起作用:

    monthly_counts = NewsFeed.select("date_trunc('month', created_at) as month, COUNT(id) as total").where("user_id NOT IN (?)",[exluded_ids]).group("month")
    monthly_counts.each do |monthly_count|
      puts "#{monthly_count.month} - #{monthly_count.total}"
    end
    

    【讨论】:

      【解决方案4】:

      http://railscasts.com/episodes/29-group-by-month

      NewsFeed.where("user_id is not in (?)",[user_ids]).group_by { |t| t.created_at.beginning_of_month } => each {|month,feed| ...}
      
      NewsFeed.select("*,MONTH(created_at) as month").where("user_id is not in (?)",[user_ids]).group("month") => ...
      

      【讨论】:

      • StatementInvalid: PG::Error: ERROR: function month(timestamp without time zone) 不存在
      【解决方案5】:

      在 Rails 5 中

      NewsFeed.select('id').group("date_trunc('month', created_at)").count
      

      【讨论】:

        猜你喜欢
        • 2018-03-06
        • 1970-01-01
        • 2019-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-05
        • 1970-01-01
        相关资源
        最近更新 更多