从数据库中选择,分组和求和结果 [英] Select, group and sum results from database

查看:153
本文介绍了从数据库中选择,分组和求和结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库,我想总结一些字段。但这不是什么大问题,我想在创建月份的时候将这些字段分组。 ActiveRecord自动创建一个名为created_at的字段。所以我的问题;

以代码更新
如何按月分组结果,然后将每个月的字段总和?

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

这是我现在的代码。按月管理分组,但未设法将我需要总结的两个字段mins和salary相加

解决方案通过使用以下方法修复它:select当获取查询时,手动输入选择

  @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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆