我有一个模型(费用),其中包含“费用”字段。查找属于当前月份(或其他月份)的条目
我想遍历我所有的费用,找到属于某个特定月份的所有条目的费用总和。
有没有办法直接在rails中执行它?
Expense.find(:全部:条件=> .....)
我有一个模型(费用),其中包含“费用”字段。查找属于当前月份(或其他月份)的条目
我想遍历我所有的费用,找到属于某个特定月份的所有条目的费用总和。
有没有办法直接在rails中执行它?
Expense.find(:全部:条件=> .....)
总和/ GROUP_BY:
Expense.find(:all,
:select => "SUM(cost) as cost_sum, MONTH(date) as month, YEAR(date) as year",
:group => "MONTH(date), YEAR(date)")
嗯......我刚刚测试过这个,它似乎在ruby 1.9.1/rails 2.3.5中工作得很好。 'Expense.find(:all,:select =>“SUM cost(cost)as cost_sum,MONTH(date)as month,YEAR(date)as year”,:group =>“MONTH(date),YEAR(date)” ).map {| x |当然,您的解决方案更多的是rails-y,但仅仅为了完整性,这个方法也可以工作。“#{x.year} _#{x.month} - #{x.cost_sum}”}' – anshul 2010-03-17 08:30:47
感谢您的代码,帮助我了解未来=) – 2014-02-12 22:57:42
要获得给定日期的月成本的总和:
# 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
选项将结果集限制为日期范围。
看一看这美丽的宝石:https://github.com/radar/by_star
http://meta.stackexchange.com/questions/23321/is-it-appropriate-to-comment-on-peoples-accept-rate/23326# 23326 – anshul 2010-03-15 03:16:55