2012-07-26 123 views
3

我有一張捐款表,我正在計算每月的總金額。對於沒有沒有任何捐款個月,我想返回的結果爲0。計算月份統計

這裏是我當前的查詢:

Donation.calculate(:sum, :amount, :conditions => { 
    :created_at => (Time.now.prev_year.all_year) }, 
    :order => "EXTRACT(month FROM created_at)", 
    :group => ["EXTRACT(month FROM created_at)"]) 

返回:

{7=>220392, 8=>334210, 9=>475188, 10=>323661, 11=>307689, 12=>439889} 

任何想法如何搶空幾個月?

回答

4

通常情況下,您將加入日曆表(或PostgreSQL中的generate_series)以獲取缺失的月份,但使用Rails最簡單的方法是將結果合併到零散列表中;像這樣:

class Donation 
    def self.by_month 
    h = Donation.calculate(:sum, :amount, :conditions => { 
     :created_at => (Time.now.prev_year.all_year) }, 
     :order => "EXTRACT(month FROM created_at)", 
     :group => ["EXTRACT(month FROM created_at)"]) 
    Hash[(1..12).map { |month| [ month, 0 ] }].merge(h) 
    end 
end 

然後只需調用類方法h = Donation.by_month即可獲得結果。

+0

哇,這正是我所期待的。萬分感謝! – tbrooks 2012-07-26 19:12:07

2

除了畝太短的回答,在3.2.12的Rails並沒有爲我工作,ActiveRecord的返回鍵爲字符串:

h = Donation.calculate(:sum, :amount, :conditions => { 
    :created_at => (Time.now.prev_year.all_year) }, 
    :order => "EXTRACT(month FROM created_at)", 
    :group => ["EXTRACT(month FROM created_at)"]) 

將返回:

{"7"=>220392, "8"=>334210, "9"=>475188, "10"=>323661, "11"=>307689, "12"=>439889} 

所以當我把散列合併爲零時:

{1=>0, 2=>0, 3=>0, 4=>0, 5=>0, 6=>0, 7=>0, 8=>0, 9=>0, 10=>0, 11=>0, 12=>0, "7"=>220392, "8"=>334210, "9"=>475188, "10"=>323661, "11"=>307689, "12"=>439889} 

小修正(to_s):

Hash[(1..12).map { |month| [ month.to_s, 0 ] }].merge(h)