【问题标题】:Laravel find difference of sum of same column with difference conditionLaravel找到具有差异条件的同一列之和的差异
【发布时间】:2021-11-11 15:37:47
【问题描述】:

我有一张包含不同类型数据的表格。我要找

sum(typeA) - sum(typeB)

类型 A = whereIn('type', ['CreditNote','ReceiptVoucher'])

类型 B = ->whereIn('type', ['DebitNote','PaymentVoucher'])

这是我想出的查询,但它不起作用。我错过了什么?

Transaction::where('contact_id',$this->contact->id)->where('date', '<', $from)
        ->where(function ($query) {
            $query
            ->whereIn('type', ['CreditNote','ReceiptVoucher'])
            ->selectRaw("SUM(amount) as in");
        })
        ->Where(function ($query) {
            $query
            ->whereIn('type', ['DebitNote','PaymentVoucher'])
            ->selectRaw("SUM(amount) as out");
        })
        ->selectRaw("COALESCE(SUM(in),0) - COALESCE(SUM(out),0) as amount")
        ->groupBy('contact_id')
        ->get();

如果我找不到这样的差异,我也可以只得到两个和,然后我可以将它们减去。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您可以使用原始查询来获取此信息,您只需为datecontact_id 指定WHERE 语句,然后对于SUM 语句,将type 条件放在IF 中像这样的声明:

    SELECT 
        SUM(// TYPE CONDITIONS FOR IN, Quantity, 0)) - SUM(IF(// TYPE CONDITIONS FOR IN, Quantity, 0)) as total
        FROM x
        WHERE ...
        GROUP BY ...;
    

    尝试原始查询后,使用 DB::raw 执行它。

    注意:不知何故,您用于别名的 inout 是 SQL 的关键字,因此请将其更改为 inQtyoutQty 或其他。

    SELECT SUM(IF(OrderDetailId 5 AND OrderDetailId 5 AND OrderDetailId

    【讨论】:

      猜你喜欢
      • 2013-07-12
      • 2023-02-06
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 2019-10-08
      • 1970-01-01
      • 2013-03-24
      相关资源
      最近更新 更多