I have request:
Model.group(:p_id).pluck(\"AVG(desired)\")
=> [0.77666666666666667e1, 0.431666666666666667e2, ...]
but when I ran SQL
Finally I've found solution:
Model.group(:p_id).pluck("p_id, AVG(Round(desired))")
=> [[1,7.76666666666667],[2,43.1666666666667], ...]
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.