Jonathan Knight
Jonathan Knight

Reputation: 61

Rails 3 Active Record Calculations: Sum and Average at the same time

Is there any way to get activerecord to calculate the sum and average of a query at the same time ?

For example I want to do something like this - which doesn't work !

Person.group("gender").count.average("age")

And get back

Gender Count Average Age

Male     32    13.5

Female   26    14.7

Upvotes: 6

Views: 3386

Answers (1)

noodl
noodl

Reputation: 17408

Person.select('gender, count(*) as count, avg(age) as avg').
       group('gender').
       order('count DESC').
       each do |p|
  puts "#{p.gender} #{p.count} #{p.avg}"
end

Not quite lickably pretty but still, not too fugly.

Upvotes: 6

Related Questions