jeudi 20 décembre 2018

How to optimize the repeated query?

I have to make a query with input date and end date. Here I have the same code repeated many times in the query. In the example below only first db_A & db_b got only where condition different with start and end value to be same.

For db_C I dont have "where('a.compid', '9')" condition and start/end date is different.

Can anybody help me how can I optimize this code ?

This is the code I have tried.

$start = date("Y-m-01", strtotime($inputdate));
$end = $inputdate;

$db_A = DB::table('standard as a')
            ->join(DB::raw("(select distinct salid, cuscod, compid from stdmap_cus) b"), function($join){
                $join->on('a.compid', '=', 'b.compid')->on('a.cuscod', '=', 'b.cuscod');
            })
            ->select('b.salid', DB::raw('sum(turnover) as sumturn'))
            ->where('a.compid', '99999999')
            ->whereBetween('date', [$start, $end])
            ->groupBy('b.salid')
            ->get()->toArray();

$res_A = $this->getSalTurn(json_decode(json_encode($db_A), true));

$db_B = DB::table('standard as a')
            ->join(DB::raw("(select distinct salid, cuscod, compid from stdmap_cus) b"), function($join){
            $join->on('a.compid', '=', 'b.compid')->on('a.cuscod', '=', 'b.cuscod');
            })
            ->select('b.salid', DB::raw('sum(turnover) as sumturn'))
            ->where('a.compid', '!=', '99999999')
            ->whereBetween('date', [$startMTD, $endMTD])
            ->groupBy('b.salid')
            ->get()->toArray();

$res_B = $this->getSalTurn(json_decode(json_encode($db_B), true));

$start = date("Y-m-01", strtotime("-1 year", strtotime($inputdate)));
$end = date("Y-m-t", strtotime("-1 year", strtotime($inputdate)));


$db_C = DB::table('standard as a')
            ->join(DB::raw("(select distinct salid, cuscod, compid from stdmap_cus) b"), function($join){
                $join->on('a.compid', '=', 'b.compid')->on('a.cuscod', '=', 'b.cuscod');
            })
            ->select('b.salid', DB::raw('sum(turnover) as sumturn'))
            ->whereBetween('date', [$startMLY, $endMLY])
            ->groupBy('b.salid')
            ->get()->toArray();
$res_C = $this->getSalTurn(json_decode(json_encode($db_C), true));



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire