Rails按时间间隔分组

时间:2015-02-12 16:32:56

标签: sql ruby-on-rails ruby activerecord

如何在没有“ruby”的情况下在sql或arel / activerecord上执行此操作?

活动计划:

integer  "action" [0,1,2]
string   "name"
float    "price"
datetime "created_at"
datetime "updated_at"

模型方法:

  # interval maybe "2 hour", "1 hour", "15 minutes" etc.
  def self.statistics(start_time, end_time, interval)
    stats = Event.where(created_at: start_time..end_time).group_by do |e|
      end_time - ((end_time - e.created_at).to_i / interval.to_f).floor * interval
    end.map do |k, e|
      gb = e.group_by {|e| e.action}
      [k,
        {
          profit: e.reduce(0) {|m, e| m += e.price},
          actions: (0..2).map {|v| gb.has_key?(v) ? gb[v].count : 0}
        }
      ]
    end.to_h

    stats
  end

输出:

{2015-10-12 11:00:00 +0300=>{:profit=>14685.0, :actions=>[86, 92, 105]},...}

0 个答案:

没有答案