You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在单条Laravel查询中获取多列分组总和的总计值?

获取Laravel分组查询的总计值解决方案

嘿,我明白你现在的需求——已经能按产品分组算出每个产品的tSaleQnt、tReturnQnt、tWasteQnt,现在想要拿到所有分组的总计值(也就是所有产品的SaleQnt总和+ReturnQnt总和+WasteQnt总和)对吧?给你几个实用的方案:

方案1:用MySQL的WITH ROLLUP直接在查询里返回总计

MySQL的WITH ROLLUP可以在分组结果的最后一行自动添加总计行,Laravel的查询构造器支持这个用法,只需要修改groupBy部分:

$return_products = DB::table('ready_products_allocate_return')
    ->join('ready_product_allocate_return_details', 'ready_product_allocate_return_details.RtnID', '=', 'ready_products_allocate_return.id')
    ->select(
        'ready_product_allocate_return_details.CatID',
        'ready_product_allocate_return_details.ItemID',
        DB::raw('sum(ready_product_allocate_return_details.SaleQnt) as tSaleQnt'),
        DB::raw('sum(ready_product_allocate_return_details.ReturnQnt) as tReturnQnt'),
        DB::raw('sum(ready_product_allocate_return_details.WasteQnt) as tWasteQnt'),
        // 直接计算当前分组的小计,方便后续提取总计
        DB::raw('sum(ready_product_allocate_return_details.SaleQnt + ready_product_allocate_return_details.ReturnQnt + ready_product_allocate_return_details.WasteQnt) as groupTotal')
    )
    ->where('ready_product_allocate_return_details.StoreID', $wrhouseID)
    ->where('ready_product_allocate_return_details.Date', $selDate)
    // 加上WITH ROLLUP,注意要把所有select里的非聚合字段都放在groupBy里
    ->groupBy('ready_product_allocate_return_details.CatID', 'ready_product_allocate_return_details.ItemID')->withRollup()
    ->get();

拿到结果后,最后一行的ItemID和CatID会是null,那就是总计行,你可以这样提取:

$grandTotal = $return_products->last()->groupTotal;

方案2:单独执行一个总计查询

如果你不需要把总计和分组结果放在一起,直接单独查总计会更简单高效:

$grandTotal = DB::table('ready_products_allocate_return')
    ->join('ready_product_allocate_return_details', 'ready_product_allocate_return_details.RtnID', '=', 'ready_products_allocate_return.id')
    ->where('ready_product_allocate_return_details.StoreID', $wrhouseID)
    ->where('ready_product_allocate_return_details.Date', $selDate)
    ->select(DB::raw('sum(SaleQnt + ReturnQnt + WasteQnt) as grandTotal'))
    ->value('grandTotal');

这个方法直接返回一个数值,省去了处理分组结果的步骤,适合只需要总计的场景。

方案3:在Laravel集合层面计算

如果已经拿到了分组后的$return_products集合,也可以用集合的方法来计算总计,不用再额外查询数据库:

$grandTotal = $return_products->sum(function ($item) {
    return $item->tSaleQnt + $item->tReturnQnt + $item->tWasteQnt;
});

这种方法的好处是复用已有的查询结果,适合已经获取了分组数据之后再补算总计的情况。

内容的提问来源于stack exchange,提问作者Ohidul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 14:22:37