如何根据sales_order_id(MySQL)汇总所有价格

时间:2014-08-19 13:59:44

标签: mysql database group-by sum sql-order-by

我正在检索销售记录,其产品已订购。我想根据其order_id 添加或总结 product_price 的所有

我当前的查询如下所示: enter image description here

问题:当我输入 SUM(bsb.PRICE)时, MySql正在合并所有产品价格。 enter image description here

这是我使用的查询:

SELECT * FROM (

SELECT bsb.ORDER_ID AS order_id, bsd.PRICE AS shipping_total, SUM(bsb.PRICE) AS product_price, '' AS order_total
FROM b_sale_basket bsb
INNER JOIN b_sale_order bso ON bso.ID = bsb. ORDER_ID
INNER JOIN b_sale_delivery bsd ON bso.DELIVERY_ID = bsd.ID
INNER JOIN b_sale_pay_system bsps ON bso.PAY_SYSTEM_ID = bsps.ID
WHERE bsb.ORDER_ID IN (255, 300)

) sales_order

注意:我想要的输出是根据order_id 对所有product_price 求和。所以最终输出应该有2行而不是1行

请帮帮我......

2 个答案:

答案 0 :(得分:1)

您必须指定编译器应如何处理未在聚合函数中使用的所有列,即SUMAVGMIN,{{}} { {1}},MAX。在你的情况下,你必须说编译器,你想要"对于每个......总和......",所以COUNT

GROUP BY bsb.order_id

答案 1 :(得分:1)

然后只需在订单ID上使用group by,这将告诉MySQL您希望如何聚合您的值:

SELECT 
  bsb.ORDER_ID AS order_id, 
  bsd.PRICE AS shipping_total, 
  SUM(bsb.PRICE) AS product_price, 
  '' AS order_total
FROM b_sale_basket bsb
INNER JOIN b_sale_order bso ON bso.ID = bsb. ORDER_ID
INNER JOIN b_sale_delivery bsd ON bso.DELIVERY_ID = bsd.ID
INNER JOIN b_sale_pay_system bsps ON bso.PAY_SYSTEM_ID = bsps.ID
WHERE bsb.ORDER_ID IN (255, 300)
GROUP BY bsb.ORDER_ID