2013-06-05 62 views
1

我有記錄在我的數據庫,如:如何計算一段時間內的物品?

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

我通過「每日項目」希望他們小組,「每個小時的項目」,「每20分鐘項目」。

實施它的最佳方法是什麼?

+3

來實現,這將是與SQL的最好方法。類似於'SELECT COUNT(id)FROM db WHERE time_field BETWEEN TO_DATE('2013/6/5','yyyy/mm/dd')和TO_DATE('2013/6/6','yyyy/mm/dd') '。雖然,取決於你的數據庫。不同的日期/時間範圍的SQL。 –

+0

如果我們使用動態切換器,例如圖表。通過1個請求獲取所有記錄並將其拆分爲'items.split_by_day(1)'將會很酷。它返回我陣列的數組,我們重建圖表沒有請求。 – bravedick

回答

3

最簡單的方法:

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]} 
1
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"]]}}