【问题标题】:Group Query in Rails ActiveRecordRails ActiveRecord 中的分组查询
【发布时间】:2014-06-30 20:29:08
【问题描述】:

我正在尝试使用 Rails 中的 ActiveRecord 对具有以下结构的表进行分组(sql 查询):

id (integer)
user_id (integer, foreign key from the users table)
work_date (date, e.g., 2014-06-02)
computed_hours (integer, e.g., 4)
computed_minutes (integer, e.g., 30)

我希望查询返回特定用户在特定月份的每一天的总计算小时数和计算分钟数的总和:

所以,比如说,user_id = 2,我希望它返回

2014-06-02 4.5(computed_hours 和 computed_minutes 总计) 2014-06-05 3.25 ......

假设上面的表格被称为 billables 并且对应的模型的名称是 Billable,这怎么能写在 ActiveRecord 中?

提前感谢您的宝贵时间。

【问题讨论】:

    标签: sql ruby-on-rails activerecord group-by


    【解决方案1】:

    假设您将 user_id 和月份(作为日期的一部分)作为参数传递,这应该可以:

    userid      = params[:user_id]
    date_start  = Date.parse(params[:date]).at_beginning_of_month - 1.days
    date_end    = Date.parse(params[:date]).at_end_of_month       + 1.days
    
    Billable.all.
             select('work_date, 
                     sum(computed_hours)   as total_hours,
                     sum(computed_minutes) as total_minutes').
             where( 'user_id = ? and (work_date > ? and work_date < ?)', 
                     userid, date_start, date_end).
             group( :work_date)
    

    然后,对于结果行中的每个 @billable,您将拥有:

    @billable.user_id
    @billable.total_hours
    @billable.total_minutes
    

    更新

    如果您正在使用 Postgres,这将产生一个难以想象的错误,您可以轻松覆盖该错误。

    生成的 SQL 将尝试按 "billable"."id" 对查询进行排序,这将导致 Postgres 也需要使用 GROUP BY "billable"."id"

    您可以绕过此行为,只需请求 NO ORDERING 或按您选择的字段排序(在本例中应为 work_date)。

    因此,解决方案需要将最后一行更改为:

             group(:work_date).order(false)
    

             group(:work_date).order(:work_date)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-31
      • 2019-02-15
      相关资源
      最近更新 更多