简体   繁体   中英

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

在此处输入图片说明

Here's my sales table

实际销售表

Since they're both identical except for an integer, you could simply do this:

Sale::whereIn('branch_id', [1, 2])->...

... and let the rest of the query stay the same.

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.

Try This.

DB::table('Sale')->whereIn('branch_id',[1,'2])->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM