Reputation: 1026
I am getting the average of all of the calls that belong to a user. A user can have many phones. So I search all the phones that belong to that user and average that phones calls and add it to an array. Now I need to average all of the calls together. This is what comes back:
[{["2009-08-14", #<BigDecimal:87e1488,'0.81E2',4(8)>]=>nil,
["2009-08-15", #<BigDecimal:87e12d0,'0.8100081168 83117E2',20(20)>]=>nil,
["2009-08-17", #<BigDecimal:87e11a4,'0.81E2',4(8)>]=>nil,
["2009-08-18", #<BigDecimal:87e108c,'0.8100167224 08027E2',20(20)>]=>nil,
["2009-08-19", #<BigDecimal:87e0f74,'0.8100543478 26087E2',20(20)>]=>nil},
{["2009-08-14", #<BigDecimal:87dd16c,'0.81E2',4(8)>]=>nil,
["2009-08-15", #<BigDecimal:87dd054,'0.8100081168 83117E2',20(20)>]=>nil,
["2009-08-17", #<BigDecimal:87dcf3c,'0.81E2',4(8)>]=>nil,
["2009-08-18", #<BigDecimal:87dcd0c,'0.8100167224 08027E2',20(20)>]=>nil,
["2009-08-19", #<BigDecimal:87dc8fc,'0.8100543478 26087E2',20(20)>]=>nil}]
Each hash is a different phone. What is the best/fastest way of averaging these together?
Upvotes: 0
Views: 710
Reputation: 17790
Do you really need to fetch the phones themselves, or are you simply looking for the average value?
If you have a :has_many set up between users and phones, you can do the following.
user.phones.average(:call_count)
(Obviously, you need to replace your real field names in there.)
That will generate a query similar to this:
SELECT avg(`phones`.call_count) AS avg_call_count FROM `phones` WHERE (`phones`.user_id = 1)
Upvotes: 1