【问题标题】:How do I count items for some time period?我如何计算一段时间内的项目?
【发布时间】:2013-06-05 15:05:27
【问题描述】:

我的数据库中有如下记录:

id | item_name | 2013-06-05T17:55:13+03:00 

我想按“每天的项目数”、“每小时的项目数”、“每 20 分钟的项目数”对它们进行分组。

实现它的最佳方法是什么?

【问题讨论】:

  • 最好的实现方式是使用 SQL。类似于SELECT COUNT(id) FROM db WHERE time_field BETWEEN TO_DATE('2013/6/5', 'yyyy/mm/dd') AND TO_DATE('2013/6/6', 'yyyy/mm/dd')。不过,这取决于您的数据库。不同日期/时间范围的不同 SQL。
  • 如果我们使用动态切换器,例如图表。通过 1 个请求获取所有记录并将它们拆分为 items.split_by_day(1) 会很酷。它返回给我数组数组,我们无需请求即可重建图表。

标签: ruby datetime time


【解决方案1】:

简单的方法:

by_day = array.group_by{|a| a.datetime.to_date}
by_hour = array.group_by{|a| [a.datetime.to_date, a.datetime.hour]}
by_20_minutes = array.group_by{|a| [a.datetime.to_date, a.datetime.hour, a.datetime.minute/20]}

【讨论】:

    【解决方案2】:
    require 'time'
    
    def group_by_period(items)
      groups = { :day => {}, :hour => {}, :t20min => {} }
      items.reduce(groups) do |memo, item|
        # Compute the correct buckets for the item's timestamp.
        timestamp = Time.parse(item[2]).utc
        item_day = timestamp.to_date.to_s
        item_hour = timestamp.iso8601[0..12]
        item_20min = timestamp.iso8601[0..15]
        item_20min[14..18] = (item_20min[14..15].to_i / 20) * 20
        # Place the item in each bucket.
        [[:day,item_day], [:hour,item_hour], [:t20min,item_20min]].each do |k,v|
          memo[k][v] = [] unless memo[k][v]
          memo[k][v] << item
        end
        memo
      end
    end
    
    sample_db_output = [
      [1, 'foo', '2010-01-01T12:34:56Z'],
      [2, 'bar', '2010-01-02T12:34:56Z'],
      [3, 'gah', '2010-01-02T13:34:56Z'],
      [4, 'zip', '2010-01-02T13:54:56Z']
    ]
    
    group_by_period(sample_db_output)
    # {:day=>
    #   {"2010-01-01"=>[[1, "foo", "2010-01-01T12:34:56Z"]],
    #    "2010-01-02"=>
    #     [[2, "bar", "2010-01-02T12:34:56Z"],
    #      [3, "gah", "2010-01-02T13:34:56Z"],
    #      [4, "zip", "2010-01-02T13:54:56Z"]]},
    #  :hour=>
    #   {"2010-01-01T12"=>[[1, "foo", "2010-01-01T12:34:56Z"]],
    #    "2010-01-02T12"=>[[2, "bar", "2010-01-02T12:34:56Z"]],
    #    "2010-01-02T13"=>
    #     [[3, "gah", "2010-01-02T13:34:56Z"], [4, "zip", "2010-01-02T13:54:56Z"]]},
    #  :t20min=>
    #   {"2010-01-01T12:20:00"=>[[1, "foo", "2010-01-01T12:34:56Z"]],
    #    "2010-01-02T12:20:00"=>[[2, "bar", "2010-01-02T12:34:56Z"]],
    #    "2010-01-02T13:20:00"=>[[3, "gah", "2010-01-02T13:34:56Z"]],
    #    "2010-01-02T13:40:00"=>[[4, "zip", "2010-01-02T13:54:56Z"]]}}
    

    【讨论】:

      猜你喜欢
      • 2014-10-17
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 2021-08-05
      • 2014-12-05
      • 1970-01-01
      • 2019-04-15
      相关资源
      最近更新 更多