【问题标题】:Laravel Query CASE with WHEREBETWEENLaravel 使用 WHEREBETWEEN 查询 CASE
【发布时间】:2021-08-03 02:17:12
【问题描述】:

我有以下疑问:

    $ordersAllProducts=Product::groupBy('products.SKU')
        ->selectRaw('products.SKU,
        (CASE
        WHEN sum(orders.quantity)>1 THEN sum(orders.quantity)
        ELSE 0
        END) as quantity_sum')
        ->leftjoin('orders','products.SKU','=','orders.SKU')
        ->get();

一切都很好,但我需要返回特定日期之间的 orders.quantity 的总和。

我试过这段代码:

$ordersAllProducts=Product::groupBy('products.SKU')
            ->selectRaw('products.SKU,
            (CASE
            WHEN sum(orders.quantity)>1 THEN sum(orders.quantity)
            ELSE 0
            END) as quantity_sum')
            ->whereBetween('date', [$from, $toTime->format('Y-m-d H:i:s')])
            ->leftjoin('orders','products.SKU','=','orders.SKU')
            ->get();

效果很好,但突然之间,并非产品(左表)中的所有字段都已连接,即

Before Between Dates(显示所有日期的数量总和):

+-----+--------+
|SKU  |Quantity|
|ABC  | 10     |
|DEF  | 20     |
|XYZ  | 40     |
+-----+--------+

After Between Dates(现在 DEF 在日期之间没有订单)

+-----+--------+
|SKU  |Quantity|
|ABC  | 8      |
|XYZ  | 14     |
+-----+--------+

我想要的输出如下(DEF 显示 0)

+-----+--------+
|SKU  |Quantity|
|ABC  | 8      |
|DEF  | 0      |
|XYZ  | 14     |
+-----+--------+

非常感谢任何帮助!

【问题讨论】:

    标签: sql laravel


    【解决方案1】:

    过滤日期的 where 条件可能是过滤连接中的空结果,即当 DEF 为 0 时。

    您可以考虑在订单表的连接中进行过滤,例如

    $ordersAllProducts=Product::groupBy('products.SKU')
                              ->selectRaw('products.SKU,
                                          (CASE
                                               WHEN sum(orders.quantity)>1 THEN sum(orders.quantity)
                                               ELSE 0
                                           END) as quantity_sum')
                     
                              ->leftjoin('orders',function($ordersJoin) use($from,$toTime){
                                  $ordersJoin->on('products.SKU','=','orders.SKU');
                                  $ordersJoin->whereBetween('date', [$from, $toTime->format('Y-m-d H:i:s')]);
                              })
                            ->get();
    

    让我知道这是否适合你。

    【讨论】:

      猜你喜欢
      • 2018-09-09
      • 2016-11-27
      • 1970-01-01
      • 2020-12-17
      • 2018-09-27
      • 2020-01-05
      • 2014-11-29
      • 2020-05-11
      • 2021-11-19
      相关资源
      最近更新 更多