Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 387
Jonathan Knight Avatar asked Jan 20 '11 11:01

Jonathan Knight


1 Answers

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.

like image 158
noodl Avatar answered Oct 23 '22 05:10

noodl