ActiveRecord AVG calculation

≡放荡痞女 提交于 2019-12-02 16:49:52

问题


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 BigDecimals 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!