cabs cabs - 3 months ago 34
MySQL Question

How to combine two queries from the same table using Laravel query builder

From this sales table, I created 2 queries.

Sale::where(branch_id', 1)->select('*', DB::raw('SUM(amount) as amount))->groupBy('date')->get()

Sale::where(branch_id', 2)->select('*', DB::raw('SUM(amount) as amount))->groupBy('date')->get()


I want to combine the two queries...

to achieve this

enter image description here

Here's my sales table

actual sales table

Answer

I think what you're looking for in raw SQL is this:

SELECT 
    `date`,
    SUM(IF(branch_id = 1, amount, 0)) as 'Branch 1',
    SUM(IF(branch_id = 2, amount, 0)) as 'Branch 2',
    SUM(amount) as 'Total'
FROM
    branches
WHERE
    branch_id IN (1,2)
GROUP BY
    `date`;

Unfortunately you can't do most of this with querybuilder, so you'll need to do it with DB::raw(), something like this:

Sale::whereIn(branch_id', [1,2])->
        select('date',
                DB::raw("
                    SUM(IF(branch_id = 1, amount, 0)) as 'Branch 1',
                    SUM(IF(branch_id = 2, amount, 0)) as 'Branch 2',
                    SUM(amount) as amount
                    ")
                )->groupBy('date')->get();

I haven't tested this in Laravel so it may be slightly off, but it should get you close.

Sample fiddle.

Comments