2010-03-15 81 views
0

我有一個模型(費用),其中包含「費用」字段。查找屬於當前月份(或其他月份)的條目

我想遍歷我所有的費用,找到屬於某個特定月份的所有條目的費用總和。

有沒有辦法直接在rails中執行它?

Expense.find(:全部:條件=> .....)

+1

http://meta.stackexchange.com/questions/23321/is-it-appropriate-to-comment-on-peoples-accept-rate/23326# 23326 – anshul 2010-03-15 03:16:55

回答

1

總和/ GROUP_BY:

Expense.find(:all, 
      :select => "SUM(cost) as cost_sum, MONTH(date) as month, YEAR(date) as year", 
      :group => "MONTH(date), YEAR(date)") 
+0

嗯......我剛剛測試過這個,它似乎在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

+0

感謝您的代碼,幫助我瞭解未來=) – 2014-02-12 22:57:42

5

要獲得給定日期的月成本的總和:

# 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選項將結果集限制爲日期範圍。

相關問題