如何比较一个字段与另一个字段的总和?

时间:2016-08-18 18:27:48

标签: mysql sum outer-join

我的数据集是这样的:

  • Total_Order_Table
  • Order_no(唯一)
  • Shipped_quantity
  • Order_Detail_Table
  • Order_number(非唯一)
  • Quantity_per_bundle

我需要从Order_Detail_Table中获取每个order_number的Quantity_per_bundle总和,并将其与Shipped_quantity进行比较。

我的想法是外部联接,以便我的数据看起来像这样:

enter image description here

我需要能够查看数量差异以及两个表中是否存在订单号。

提前致谢!

2 个答案:

答案 0 :(得分:0)

除非我在问题中遗漏了一些微妙的内容,否则这不像在表之间使用连接的SELECT查询一样简单。

根据这一点,应该达到这样的结果:

SELECT  tot.Order_no,
        odt.Order_no,
        SUM(odt.Quantity_per_bundle),
        tot.Shipped_quantity
  FROM  Total_Order_Table tot
    LEFT JOIN Order_Detail_Table odt ON odt.Order_Number = tot.Order_Number
  GROUP BY tot.Order_no, odt.Order_no, tot.shipped_quantity

(代码未在MySQL中测试,因此原谅错误)

答案 1 :(得分:0)

在sql中使用FULL OUTER JOIN的Normaly:

SELECT to.Order_no AS Order_no_Total_Order_Table, od.Order_number AS Order_No_Ordr_detail_Table, SUM(od.Order_number) AS sum_Quanitty_Per_Bundle, od.Order_number 
FROM Total_Order_Table AS to
FULL OUTER JOIN Order_Detail_Table AS od ON  to.Order_no = od.Order_number
GROUP BY to.Order_no

但是mysql中不存在FULL OUTER JOIN。但你可以模拟它:http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/