【问题标题】:How to merge two rows and get result?如何合并两行并得到结果?
【发布时间】:2021-09-03 06:11:06
【问题描述】:

表格数据:

sales_products 表数据:

product_id quantity sales price
1 4 300
1 5 300
2 3 400
2 2 400
3 3 100

产品表

id product_name
1 product_x
2 product_y
3 product_z

预期的查询输出

product_name Quantity Total_Price
product_x 9 2700
product_y 5 2000
product_z 3 300

我正在尝试使用以下查询,但没有得到预期的输出

$invoiceDetails = DB::table('products')
    ->join('sales_products', 'sales_products.product_id', '=', 'products.id')
    ->select(
        'products.product_name',
        'sales_products.quantity',
        'sales_products.sales_price',
        DB::raw('(sales_products.quantity * sales_products.sales_price) as total')
    )
    ->where('sales_products.invoice_id', '=', $id)
    ->get();

【问题讨论】:

  • 您是否为这些表设置了模型?
  • 不。我没有建立任何关系
  • 你得到了哪个输出而不是预期的输出?

标签: php mysql laravel laravel-5 laravel-query-builder


【解决方案1】:
SELECT p.product_name, sp.Quantity, sp.Total_price
FROM `products` p
INNER JOIN (
    SELECT SUM(quantity) AS Quantity,
        product_id,
        SUM(sales_price*quantity) AS Total_price
    FROM `sales_products`
    GROUP BY product_id
) AS sp
    ON p.id = sp.product_id

上面的这个查询应该会有所帮助。如何合并查询是使用GROUP BY。在 product_id 的第一个表上使用 GROUP BY 有助于我们相应地总结列。

【讨论】:

    猜你喜欢
    • 2018-03-07
    • 2010-11-23
    • 2018-07-26
    • 1970-01-01
    • 2015-09-05
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多