我想在entotalitem和extotalitem之間進行減法運算,查詢我使用的是從同一個表tbl_orders_data中檢索資料。
我嘗試了建立2個查詢,第一個查詢用於檢索entotalitem,第二個查詢用於檢索extotalitem
$encheck = DB::table('tbl_orders_data') ->select('slot_id', DB::raw('sum(total_item) as entotalitem')) ->where('id_order_data', 'like', 'PBM' . '%') ->groupBy('slot_id') ->pluck('entotalitem'); $excheck = DB::table('tbl_orders_data') ->select('slot_id', DB::raw('sum(total_item) as extotalitem')) ->where('id_order_data', 'like', 'PBK' . '%') ->groupBy('slot_id') ->pluck('extotalitem'); $en = $encheck; $ex = $excheck; dd($en - $ex);
我只需要使用一個查詢嗎?還是應該像我嘗試的2個查詢? 請幫幫我,謝謝
P粉5150665182023-09-08 09:38:50
您可以在這裡使用條件聚合:
$check = DB::table('tbl_orders_data') ->select('slot_id', DB::raw("sum(case when id_order_data like 'PBM%' then total_item else 0 end) - sum(case when id_order_data like 'PBK%' then total_item else 0 end) as totalitem")) ->groupBy('slot_id') ->pluck('totalitem');