Forum: Ruby on Rails Multiple Sum/Average/Max/etc in one query

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D810e7436feb302a3e4e6b11895a7f65?d=identicon&s=25 Gael Pourriel (Guest)
on 2006-05-19 11:09
(Received via mailing list)
Hi all, I was wondering how one does multiple sum/average/max/min in a
single query using AR.

It would be cool to be able to do:

totals = Call.sum([:price,:duration], { :conditions => "destination =
'UK'", :group => "location" })

and end up with a hash with totals[:location][:colname]

e.g.:

totals['london']['price'] = 15
totals['london']['duration'] = 30
totals['leeds']['price'] = 20
totals['leeds']['duration'] = 40
totals['manchester']['price'] = 10
totals['manchester']['duration'] = 20

Ideally I would even dream about something that can do:

totals = Call.calculate([:sum,:sum,:count],[:price,:duration,:call], {
:conditions => "destination = 'UK'", :group => "source,location" })

Which would give me a hash with totals[:source][:location][:colname]

e.g.:

totals['US']['london']['price'] = 15
totals['US']['london']['duration'] = 30
totals['US']['london']['call'] = 5
totals['US']['leeds']['price'] = 20
totals['US']['leeds']['duration'] = 40
totals['US']['leeds']['call'] = 8
totals['FR']['london']['price'] = 10
totals['FR']['london']['duration'] = 20
totals['FR']['london']['call'] = 5

Any one has been confronted to this problem? How did you sort this out?

My current way of doing it is:

Call.find(:all, :select => "'price' = sum('price'), 'duration' =
sum(duration), 'call' = count(call), source, location", :conditions =>
"destination = 'UK'", :group => "source,location" )

Then I iterate through the result collection and make up the hash myself

It works fine but I was hoping to find a Rails way of doing so....

Gael
This topic is locked and can not be replied to.