ActiveRecord AVG calculation

前端 未结 2 1777
野性不改
野性不改 2021-01-27 15:02

I have request:

Model.group(:p_id).pluck(\"AVG(desired)\")
=> [0.77666666666666667e1, 0.431666666666666667e2, ...]

but when I ran SQL

相关标签:
2条回答
  • 2021-01-27 15:51

    Finally I've found solution:

    Model.group(:p_id).pluck("p_id, AVG(Round(desired))")
    => [[1,7.76666666666667],[2,43.1666666666667], ...]
    
    0 讨论(0)
  • 2021-01-27 16:07

    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.

    0 讨论(0)
提交回复
热议问题