首页 > 解决方案 > Group by 返回错误的总和

问题描述

这是我的3张桌子:

Products table: id, product_name
Purchase Product table: id, product_id, purchase_price, quantity
Sales Product table: id, product_id, sales_price, quantity, purhase_price.

我想找到购买清单和销售清单上的产品。如果它不在销售列表上,它应该返回空销售值以及数量。在这里,相同的产品具有不同的购买价格,因此我需要跟踪已售出的购买产品。但是对于 group by,它显示的总和是错误的。我的查询可能出现什么错误?

这是我的查询:

$products = DB::table('products')
    ->join('purchase_products','purchase_products.product_id','products.id')
    ->leftjoin("sales_products",function($join){
        $join
            ->on("sales_products.purchase_price","purchase_products.purchase_price")
            ->on("sales_products.product_id","purchase_products.product_id");
        })
        ->select('products.product_name','purchase_products.purchase_price',DB::raw("SUM(purchase_products.quantity) as purchase_quantity"),'sales_products.sales_price',DB::raw("SUM(sales_products.quantity) as sales_quantity"))
        ->groupby('products.id','purchase_products.purchase_price')
        ->get();

在此处输入图像描述

标签: phpmysqllaravelinner-joinlaravel-query-builder

解决方案


当您连接多个表时,求和的是连接表的每个组合。因此,如果您有两个产品的销售记录,则不同购买的总和将加倍。

我不能告诉你如何在 laravel 中做到这一点,但你可以删除你的 sales join 并使用它products.id in (select product_id from sales_products)来判断产品是否有销售,或者不要同时加入 sales_products 和 purchase_products,而是将 products 和 sales_products 加入仅返回不同产品 ID 的子查询。

或者如果你真的不想改变你的查询结构,你可以改变:

SUM(purchase_products.quantity)

SUM(purchase_products.quantity) / GREATEST(1, COUNT(sales_products.id))

顺便说一句,如果产品不在销售列表中,我看不到您在查询中将 sales 设置为 null 的位置。

此外,您可能希望按 purchase_products.id 而不是 purchase_products.purchase_price 进行分组,以防产品两次具有相同的价格。


推荐阅读