Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select, group and sum results from database

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

like image 939
ThoKra Avatar asked Oct 14 '22 13:10

ThoKra


1 Answers

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.

like image 111
timmow Avatar answered Oct 20 '22 16:10

timmow