从数据库中选择,分组和求和结果 [英] Select, group and sum results from database
问题描述
我有一个数据库,我想总结一些字段。但这不是什么大问题,我想在创建月份的时候将这些字段分组。 ActiveRecord自动创建一个名为created_at的字段。所以我的问题;
以代码更新
如何按月分组结果,然后将每个月的字段总和?
@hours = Hour.all(:conditions =>user_id =+ @ user.id.to_s,
:group => strftime('%m',created_at),
:order =>'created_at DESC')
这是我现在的代码。按月管理分组,但未设法将我需要总结的两个字段mins和salary相加
@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')
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
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')
这篇关于从数据库中选择,分组和求和结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!