Reputation: 61
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
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