Skip to content
Advertisement

How to use multiple whereBetween to sum two different record

I need to compare and sum data from two different date.

Assuming i have 4 input dates

startdate = "2020-11-01",
enddate = "2020-11-30",
compare_startdate = "2020-12-01",
compare_enddate = "2020-12-31",

Currently, my query only able to get one whereBetween date data as below

Current Code

$raw_data = ChartOfAccount::with(array(
    'journal' => function($query) use ($init)
    {
            $query->selectRaw('*,
            sum(item_journals.debit) as total_debit,
            sum(item_journals.credit) as total_credit,
            sum(item_journals.debit) - sum(item_journals.credit) as net_movement');
            $query->groupBy('chart_of_account_id');
            $query->where('item_journals.deleted_at', null);
            $query->whereBetween('date', array($init['startdate'], $init['enddate']));                
    }
    ))
    ->get();

Current result from startdate and enddate

"total_debit" => "0.00"
"total_credit" => "200.00"
"net_movement" => "-200.00"

Example another result from compare_startdate and compare_enddate

 "total_debit" => "0.00"
 "total_credit" => "50.00"
 "net_movement" => "-50.00"

How to query another result from compare_startdate to compare_enddate in order to sum result of startdate and enddate?

Expected result

"total_debit" => "0.00"
"total_credit" => "150.00"
"net_movement" => "-150.00"

I did try something like this in query but result is incorrect

$query->whereBetween('date', array($init['startdate'], $init['enddate']));                
$query->whereBetween('date', array($init['compare_startdate'], $init['compare_enddate']));                

Advertisement

Answer

Hi Friend You Can Use orWhereBetween in advance where clause as below,

DB::table('tbl')
  ->Where(function ($query) use ($startdate,$enddate,$compare_startdate,$compare_enddate) {
      $query->whereBetween('date', [$startdate, $enddate]);
      $query->orWhereBetween('date', [$compare_startdate, $compare_enddate] );
})->get();
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement