代码之家  ›  专栏  ›  技术社区  ›  ThoKra

从数据库中选择、分组和汇总结果

  •  5
  • ThoKra  · 技术社区  · 17 年前

    我有一个数据库,其中包含一些我想求和的字段。但这不是大问题,我想按创建月份对这些字段进行分组。ActiveRecord自动创建了一个名为“created_at”的字段。所以我的问题,;如何将结果按月分组,然后对每个月的字段求和?

    用代码更新

    @hours = Hour.all(:conditions => "user_id = "+ @user.id.to_s, 
                      :group => "strftime('%m', created_at)",
                      :order => 'created_at DESC')
    

    3 回复  |  直到 17 年前
        1
  •  2
  •   timmow    13 年前

    你可以用 active record calculations 这样做。一些示例代码可能是

    Model.sum(:column_name, :group => 'MONTH("created_at")')
    

    显然,警告月是特定于mysql的,所以如果您是在SQLite数据库上开发的,这是行不通的。

        2
  •  1
  •   Community Mohan Dere    9 年前

    records = Tasks.find(:conditions => {..})
    month_groups = records.group_by{|r| r.created_at.month}
    month_groups.each do |month, records|
      sum stuff.. blah blah blah..
    end
    

    我在这个问题的右边看到了这个链接。我假设除了MySQL之外,其他数据库也有类似的功能。

    mysql select sum group by date

        3
  •  1
  •   ThoKra    17 年前

    使用以下方法修复了此问题:获取查询时选择,输入手动选择

    @hours = Hour.all(:conditions => "user_id = "+ @user.id.to_s,
                      :select => "created_at, SUM(time) time",
                      :group => "strftime('%m', created_at)",
                      :order => 'created_at DESC')