Created
June 7, 2012 19:45
-
-
Save maxjustus/2891131 to your computer and use it in GitHub Desktop.
aggregate arbitrary column on time interval for charts using Postgres and ActiveRecord/Arel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module CountByInterval | |
def count_by_interval(aggregate_range = 'day', column = "#{self.table_name}.created_at", aggregate_operation = 'count(*)') | |
aggregate_on = "date_trunc('#{aggregate_range}', #{column})" | |
self.select_values = ["coalesce(#{aggregate_operation}, 0) as value", "#{aggregate_on} as date"] | |
ActiveRecord::Base.connection.execute(self.group(aggregate_on).to_sql).collect {|r| r} | |
end | |
end | |
ActiveRecord::Relation.send(:include, CountByInterval) #EWWWWwww |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
User.where(:in_space => true).count_by_interval('month', 'launched_at', 'sum(body_mass)') | |
#=> [{"value"=>"7637", "date"=>"2012-04-01 00:00:00"}, {"value"=>"963", "date"=>"2012-05-01 00:00:00"}, {"value"=>"662", "date"=>"2012-06-01 00:00:00"}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment