【问题标题】:Get average of average columns in mysql获取mysql中平均列的平均值
【发布时间】:2021-06-14 09:06:33
【问题描述】:

我有一张存储餐厅评级的表格。如下图所示。

我正在尝试获取我成功的所有这些列的平均值,但我也想要所有这些平均值的平均值作为主要平均值。

我尝试了以下查询,但平均评分为 3,这是不准确的。我认为 mysql 正在返回一个最终结果的整数值。

return $this->db->select('((ambience + music + service + value_for_money + cleanliness + sanitary + view)/7) as rating, AVG(ambience) as ambience, AVG(music) as music, AVG(service) as service,AVG(value_for_money) as value_for_money, AVG(cleanliness) as cleanliness, AVG(sanitary) as sanitary, AVG(view) as view' )
        ->where('restaurant_id',$restaurantId)
        ->get('restaurant_ratings')
        ->row_array();

当我运行上述查询时,评分字段的平均值为 3。

实际结果是 3.42。

请帮助我了解我做错了什么以及可以做些什么来获得准确的结果。 谢谢

【问题讨论】:

  • 请附上你想看的前后数据。

标签: php mysql codeigniter


【解决方案1】:

只需添加AVG 即可计算评分:

$query = 
    'AVG((
        ambience + 
        music + 
        service + 
        value_for_money + 
        cleanliness + 
        sanitary + 
        view
    )/7) as rating, 
    AVG(ambience) as ambience, 
    AVG(music) as music, 
    AVG(service) as service,
    AVG(value_for_money) as value_for_money, 
    AVG(cleanliness) as cleanliness, 
    AVG(sanitary) as sanitary, 
    AVG(view) as view';

return $this->db
            ->select($query)
            ->where('restaurant_id',$restaurantId)
            ->get('restaurant_ratings')
            ->row_array();

【讨论】:

    猜你喜欢
    • 2013-01-01
    • 2022-01-08
    • 2015-02-19
    • 2015-09-11
    • 2012-03-18
    • 2022-08-14
    • 2022-11-03
    • 1970-01-01
    相关资源
    最近更新 更多