问题
I have request:
Model.group(:p_id).pluck("AVG(desired)")
=> [0.77666666666666667e1, 0.431666666666666667e2, ...]
but when I ran SQL
SELECT AVG(desired) AS desired
FROM model
GROUP BY p_id
I got
-----------------
| desired |
|-----------------|
| 7.76666666666667|
|43.1666666666667 |
| ... |
-----------------
What is the reason of this? Sure I can multiply, but I bet where are should be an explanation.
I found that
Model.group(:p_id).pluck("AVG(desired)").map{|a| a.to_f}
=> [7.76666666666667,43.1666666666667, ...]
Now I'm struggle with other task, I need numbers attributes in pluck so my request is:
Model.group(:p_id).pluck("p_id, AVG(desired)")
how to get correct AVG value in this case?
回答1:
0.77666666666666667e1
is (almost) 7.76666666666667
, they're the same number in two different representations with slightly different precision. If you dump the first one into irb
, you'll see:
> 0.77666666666666667e1
=> 7.766666666666667
When you perform an avg
in the database, the result has type numeric
which ActiveRecord represents using Ruby's BigDecimal
. The BigDecimal
values are being displayed in scientific notation but that shouldn't make any difference when you format your data for display.
In any case, pluck
isn't the right tool for this job, you want to use average
:
Model.group(:p_id).average(:desired)
That will give you a Hash which maps p_id
to averages. You'll still get the averages in BigDecimal
s but that really shouldn't be a problem.
回答2:
Finally I've found solution:
Model.group(:p_id).pluck("p_id, AVG(Round(desired))")
=> [[1,7.76666666666667],[2,43.1666666666667], ...]
来源:https://stackoverflow.com/questions/47588382/activerecord-avg-calculation