0

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?

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately the way my database is set up, I have to get the average like I do above.
Can you clean up your array of hashes above? It's unclear what values exactly you're trying to average.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.