Ruby on Rails:如何使用PG获得每月计数

时间:2014-12-20 14:56:55

标签: postgresql ruby-on-rails-4 rails-activerecord

现在我正面临一个问题,就是我想写一份声明来回报月计数,

例如,在2014-01至2014-12期间。返回像

这样的订单数组
["Jan, 5", "Feb, 0",...,"Dec, 55" ]

我唯一知道的可能解决方案是

1. get a scope to return monthly record
2. calculate the period number, like here is 12 
3. repeat 12.times to get record size for each month
4. build array

问题是我必须重复查询12次!这太奇怪了。 我知道group_by可能是更好的选择,但不知道如何实现我真正想要的性能。谁能帮助我?

2 个答案:

答案 0 :(得分:1)

使用Postgres's to_char格式化日期列,然后在ActiveRecord的组方法中使用它。

start = Date.new(2014, 1, 1)
finish = Date.new(2014, 12, 31)

range = start..finish

return_hash = ModelClass.
              where(created_at: range).
              group("to_char(created_at, 'Mon YYYY')").
              count

这将返回类似{"Nov 2014" => 500}

的哈希值

要填补空白,您可以创建month_names数组并执行:

month_names.each{ |month| return_hash[month] ||= 0 }

考虑创建一个新哈希,其密钥根据您的month_names变量进行排序。

然后获得所需的输出:

return_hash.map{ |month, count| "#{month}, #{count}" }

答案 1 :(得分:0)

我使用groupdate gem(https://github.com/ankane/groupdate

然后将.group_by_month(:created_at).count添加到您的查询