Select, group and sum results from database

安稳与你 提交于 2019-12-22 07:21:04

问题


I have a database with some fields I'd like to sum. But that's not the big problem, I want to group those fields by the month they were created. ActiveRecord automaticaly created a field named "created_at". So my question; how can I group the result by month, then sum the fields for each month?

Updated with code

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

This is the code I have now. Managed to group by month, but doesn't manage to sum two of my fields, "mins" and "salary" which I need to sum


回答1:


You can use active record calculations to do this. Some example code might be

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

Obviously with the caveat MONTH is mysql specific, so if you were developing on an SQLite database this would not work.




回答2:


I don't know if there's a SQL query you use to do it (without changing your current table structure). However, you do it with some lines of code.

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

I saw this link on the right side of this question. I assume other databases, besides MySQL have similar functions.

mysql select sum group by date




回答3:


Fixed it by using :select when getting the query, inputing selects manually

@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')


来源:https://stackoverflow.com/questions/1556289/select-group-and-sum-results-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!