Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get Aggregate Data by Time Slice (sum, avg, min, max, etc.) in Rails 3

How can I create active relation queries in Rails 3 that are aggregated by time slice?

I'd like to build queries that for every n minute interval can return min, max, avg, sum, count, for every sample of a counter with a particular name.

create_table "samples"  
    t.integer  "counter_id"  
    t.string "name"  
    t.float    "value"  
    t.datetime "created_at"  
end  
like image 487
ebeland Avatar asked Mar 04 '11 18:03

ebeland


1 Answers

Unfortunately I've never used Postgres, so this solution works in MySQL. But I think you can find out Postgres analogs.

class Counter < ActiveRecord::Base
  has_many :samples do
    # default 30 minutes
    def per_time_slice(slice = 30)
      start = "2000-01-01 00:00:00"
      self.select("*, 
                   CONCAT( FLOOR(TIMESTAMPDIFF(MINUTE,'#{start}',created_at)/#{slice})*#{slice},  
                     (FLOOR(TIMESTAMPDIFF(MINUTE,'#{start}',created_at)/#{slice})+1)*#{slice} ) as slice,
                   avg(value) as avg_value, 
                   min(value) as min_value, 
                   max(value) as max_value, 
                   sum(value) as sum_value, 
                   count(value) as count_value").
                   group("slice").order("slice")
    end
  end
end

Usage

counter = find_some_counter
samples = counter.samples.per_time_slice(60).where(:name => "Bobby")
samples.map(&:avg_value)
samples.map(&:min_value)
samples.map(&:max_value)

etc

like image 171
fl00r Avatar answered Nov 03 '22 07:11

fl00r