ActiveRecord AVG计算 [英] ActiveRecord AVG calculation

查看:77
本文介绍了ActiveRecord AVG计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有请求:

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

但是我运行SQL

SELECT AVG(desired) AS desired
FROM model
GROUP BY p_id

我得到了

 -----------------
|      desired    |
|-----------------|
| 7.76666666666667|
|43.1666666666667 |
|       ...       |
 -----------------

这是什么原因呢?当然可以乘,但是我敢打赌哪里应该是个解释。

What is the reason of this? Sure I can multiply, but I bet where are should be an explanation.

我发现

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)") 

在这种情况下如何获取正确的AVG值?

how to get correct AVG value in this case?

推荐答案

0.77666666666666667e1 (几乎) 7.76666666666667 ,它们是两个不同表示形式中的相同数字,但精度略有不同。如果将第一个转储到 irb 中,则会看到:

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 

在执行 avg 时数据库,结果的类型为数字,ActiveRecord使用Ruby的 BigDecimal 表示。 BigDecimal 值以科学计数法显示,但是在设置数据格式以进行显示时应该没有任何区别。

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.

在任何情况下, pluck 都不适合该工作,您想使用平均值

In any case, pluck isn't the right tool for this job, you want to use average:

Model.group(:p_id).average(:desired)

这将为您提供一个将 p_id 映射到平均值的哈希。您仍然可以在 BigDecimal s中获得平均值,但这确实不成问题。

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.

这篇关于ActiveRecord AVG计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆