Laravel 8分组查询中如何将sum(weight)结果除以分组记录数取平均值
解决方案
你可以直接使用SQL原生的AVG()聚合函数实现平均值计算,这是最简便的实现方式,修改查询中的selectRaw部分即可:
$itemsAll = $this->selectedProductIngredient->with(['item']) // 注意:如果MySQL开启严格模式,select里的非分组字段product_id会报错,不需要可以删掉,需要的话要加入groupBy ->select('ingredient_id') ->selectRaw('AVG(weight) as weight_sum') // 把SUM替换为AVG即可 ->where('single_product_analysis_id', 0) ->where('group_id', $id) ->where('type', 2) ->groupBy('ingredient_id') ->orderByDesc('weight_sum') ->get();
补充说明
如果你需要同时保留分组的总重量、记录条数和平均值,也可以同时查询多个聚合字段:
$itemsAll = $this->selectedProductIngredient->with(['item']) ->select('ingredient_id') ->selectRaw('SUM(weight) as weight_sum, COUNT(*) as group_count, AVG(weight) as weight_avg') ->where('single_product_analysis_id', 0) ->where('group_id', $id) ->where('type', 2) ->groupBy('ingredient_id') ->orderByDesc('weight_avg') ->get();
注意原查询中
select包含的product_id字段,在MySQL严格模式(Laravel 8默认开启)下,未出现在groupBy条件中也未使用聚合函数的字段会触发SQL错误,如果你不需要按product_id分组,可以直接删除该字段的选择;如果需要多字段分组,将groupBy('ingredient_id')改为groupBy(['ingredient_id', 'product_id'])即可。
内容的提问来源于stack exchange,提问作者triop
相关产品推荐
相关产品推荐

