繁体   English   中英

MySQL ROUND和AVG无法正常工作

[英]MySQL ROUND and AVG not working as expected

您好我想使用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();
    }

在这里,我试图获取AvarageRating值后的AvarageRating

我只有一条记录与该行中的条件匹配, AvarageRating值为4.5

但查询结果是

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

)

当我删除ROUND它可以正常工作,但是我想在获得平均值之前四舍五入AvarageRating

在这种情况下,我期望4.5是结果,为什么它返回4

请帮助,在此先感谢。

ROUND(AvarageRating,1)

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

您要让它四舍五入为4.5至0小数位,然后取平均值。

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

对答案应为4还是5的WRT,请特别注意文档的这一部分:

“对于近似值数字,结果取决于C库。在许多系统上,这意味着ROUND()使用“四舍五入到最接近的偶数”规则:任何小数部分的值都将四舍五入到最接近的偶数整数。”

暂无
暂无

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

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