简体   繁体   English

MySQL ROUND和AVG无法正常工作

[英]MySQL ROUND and AVG not working as expected

hi i am tying to use mysql ROUND and AVG functions , 您好我想使用mysql ROUNDAVG函数,

public function get_average_rating_by_specialty($shop_id,$where_array=array())
    {

        $this->replica->select('PreferenceToLOBID,PreferenceID , AVG(ROUND(AvarageRating)) as AvarageRating');
        $this->replica->from('*******');
        $this->replica->where(array('ShopID'=>$shop_id,'IsDelete'=>0));

        if($where_array)
        {
            $this->replica->where($where_array);
        }

        $this->replica->group_by('PreferenceID,PreferenceToLOBID');     
        $result = $this->replica->get();


        return $result->result_array();
    }

here im trying to get average values after round the AvarageRating value, 在这里,我试图获取AvarageRating值后的AvarageRating

i have only one record that matches my conditions in that row the AvarageRating value is 4.5 我只有一条记录与该行中的条件匹配, AvarageRating值为4.5

but the query result is 但查询结果是

Array
(
    [0] => Array
        (
            [PreferenceToLOBID] => 29
            [PreferenceID] => 654
            [AvarageRating] => 4.0000
        )

)

when i remove ROUND this works correctly , but i want to round the AvarageRating values before get the average 当我删除ROUND它可以正常工作,但是我想在获得平均值之前四舍五入AvarageRating

in this case i expect 4.5 to be the result , why it's returning 4 在这种情况下,我期望4.5是结果,为什么它返回4

please help , thanks in advance. 请帮助,在此先感谢。

ROUND(AvarageRating,1)

那么你可以得到想要的4,5

You're asking it to round 4.5 to 0 decimal places, and then average it. 您要让它四舍五入为4.5至0小数位,然后取平均值。

See http://dev.mysql.com/doc/refman/5.1/en/mathematical-functions.html#function_round 参见http://dev.mysql.com/doc/refman/5.1/en/mathematical-functions.html#function_round

WRT to whether the answer should be 4 or 5, pay special attention to this part of the docs: 对答案应为4还是5的WRT,请特别注意文档的这一部分:

"For approximate-value numbers, the result depends on the C library. On many systems, this means that ROUND() uses the "round to nearest even" rule: A value with any fractional part is rounded to the nearest even integer." “对于近似值数字,结果取决于C库。在许多系统上,这意味着ROUND()使用“四舍五入到最接近的偶数”规则:任何小数部分的值都将四舍五入到最接近的偶数整数。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM