我有一个模型(费用),其中包含像“成本”这样的字段。
我想遍历我的所有费用,以找到属于特定月份的所有条目的成本总和。
有没有办法直接在rails中做到这一点?
Expense.find(:all,:conditions => .....)
发布于 2010-03-15 11:33:04
要获取给定日期当月的成本总和,请执行以下操作:
# date = any day of the month of intrest
Expense.sum(:cost, :conditions => {:created_at =>
(date.beginning_of_month..date.end_of_month)})要获得所有月份的成本总和,请执行以下操作:
Expense.sum(:cost,
:group => "EXTRACT(YEAR_MONTH FROM created_at)").each do |y_m, cost_sum|
p "#{y_m}-#{cost_sum}"
end在上面的调用中,使用conditions选项将结果集限制为一个日期范围。
发布于 2010-03-15 10:43:27
sum/group_by:
Expense.find(:all,
:select => "SUM(cost) as cost_sum, MONTH(date) as month, YEAR(date) as year",
:group => "MONTH(date), YEAR(date)" )发布于 2013-03-04 12:10:36
看看这颗美丽的宝石:https://github.com/radar/by_star
https://stackoverflow.com/questions/2444470
复制相似问题