Laravel 条件聚合获取多个金额之和

Larave conditional aggregation to get multiple sum of amount

希望一切都好。

任何人都可以告诉我如何在 Laravel 中以正确的方式到达 运行 这个 SQL 查询?

控制器:

     $data=DB::raw("SELECT name as 'name' FROM invoices WHERE country='$country';
            SELECT SUM(amount) as 'income' FROM invoices WHERE (country='$country' AND type='income');
            SELECT SUM(amount) as 'outcome' FROM invoices WHERE (country='$country' AND type='outcome')")
            ->groupBy('name')
            ->get();

        return view('accounting.accounts')
        ->with('accounts',$data);

我希望在我看来使用它如下:

@foreach($accounts as $account)
       <tr>
        <th>{{$account->name}}</th>
        <td>{{$account->income}}</td>
        <td>{{$account->outcome}}</td>
       </tr>
@endforeach
    

我是 Laravel 的新手,非常感谢您的帮助。 提前谢谢你。

我相信您想要一个聚合查询,其中包含特定国家/地区内每个用户的条件金额总和。 在纯 SQL 中,它可以使用 CASE 语句作为

select  name,
        sum(case when type='income' then amount else 0 end) as income,
        sum(case when type='outcome' then amount else 0 end) as outcome
from invoices
where country = :country
group by name
order by name

在查询生成器中,它可以转换为

$accounts= DB::table("invoices")
            ->where("country", $country)
            ->select([ "name",
                        DB::raw("sum(case when type='income' then amount else 0 end) as income"),
                        DB::raw("sum(case when type='outcome' then amount else 0 end) as outcome")
                    ])
            ->groupBy("name")
            ->orderBy("name")
            ->get();