[SOLVED] How to calculate subtraction of 2 Sql Query

Issue

I want to do a subtraction operator between entotalitem and extotalitem.query that I use retrieve data from the same table that is tbl_orders_data.

I have tried by creating 2 queries, the first is the query to retrieve entotalitem and the second query to retrieve 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);

Should I only need to use one query? or should I make 2 queries as I have tried?
please help me, thanks

Solution

You may use conditional aggregation here:

$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');

Answered By – Tim Biegeleisen

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.