0

我需要生成一个报告,该报告返回给定时间范围内的一组数字。

例如,我需要返回给定月份的观看分钟数。这是我现在运行的

presentation = Presentation.find(1)
presentation.video.stats.minutes_by_date(Date.new(2012,6,1),Date.new(2012,6,30))


def self.by_date(start_date,end_date)
    vals = Array.new
    (start_date..end_date).map { |date|
      yesterdays_stat = daily_watched(date.yesterday)
      todays_stat = daily_watched(date)

      if todays_stat > 0
        if yesterdays_stat > 0
          difference = todays_stat - yesterdays_stat
        else
          difference = todays_stat
        end
        watched_in_meg = (difference / 1024).round(2)
        vals.push (watched_in_meg / first.video.meg_per_minute).round(2)
      else
        vals.push 0
      end
    }
    vals
  end

  def self.daily_watched(date)
    # get the total bytes for the from both flash and mp4
    total_bytes = 0
    bytes = where(["DATE(generated_date) = ?", date]).group("kbytes")
    .order('generated_date')
    bytes.each do |byte|
      total_bytes += byte.kbytes
    end
    total_bytes
    # Get the bytes of both flash and mp4
  end

输出需要如下所示:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 0]

问题是每个演示文稿必须运行 30 次,而我有 10 到 500 个演示文稿。

有没有办法提高效率?

4

2 回答 2

1

您可以从通过单个查询获取所有日期的统计信息开始,然后通过一次遍历数组来计算差异。

查询大致如下所示:

result = Thing.select("DATE(generated_date) as date, SUM(kbytes) as sum_kbytes").group("DATE(generated_date)").where...
result.each{|i| puts "#{i.date} #{i.sum_kbytes}"}
于 2012-07-05T19:29:33.517 回答
0

预先计算每天每个演示文稿的差异 var。然后从这个函数中的预先计算的表中读取。

于 2012-07-05T18:24:47.437 回答