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

2 回答 2

4

通常你会离开加入日历表(或generate_series在 PostgreSQL 中)来获取缺失的月份,但使用 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即可获得结果。

于 2012-07-26T18:57:23.333 回答
2

除了mu 太短的答案,在 Rails 3.2.12 对我不起作用,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)
于 2014-01-16T00:48:58.537 回答