2

この sales テーブルから、2 つのクエリを作成しました。

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()

2つのクエリを結合したい...

これを達成するために

ここに画像の説明を入力

これが私の売上表です

実売表

4

3 に答える 3

3

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.

于 2016-08-11T16:05:44.027 に答える
2

生のSQLで探しているのはこれだと思います:

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`;

残念ながら、これのほとんどは querybuilder では実行できないため、次のDB::raw()ように で実行する必要があります。

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();

私はこれを Laravel でテストしていないので、少しずれているかもしれませんが、近いはずです。

サンプルフィドル。

于 2016-08-11T17:10:45.690 に答える
0

これを試して。

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

于 2016-08-11T16:38:22.353 に答える