【问题标题】:Larave conditional aggregation to get multiple sum of amountLaravel条件聚合以获得多个金额总和
【发布时间】:2021-04-29 15:28:04
【问题描述】:

希望一切都好。

谁能告诉我如何在 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 查询? 也就是说,你想用 Eloquent 编写这个请求,对吧?
  • 雄辩或原始,我只需要检索请求的数据。它似乎不像我发布的那样工作
  • 它不会按照您发布的方式工作。您有三个单独的查询,它们之间没有明显的联系。可能可以提取您想要的数据,但是对于您的架构,不可能看到如何。

标签: php sql laravel sum aggregate-functions


【解决方案1】:

我相信您需要一个聚合查询,其中包含特定国家/地区内每个用户的条件总和。 在纯 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    相关资源
    最近更新 更多