在Mysql

时间:2016-05-19 11:00:05

标签: php mysql database

我在MySQL数据库中有两个表,即表A和表B.当prod_1在发票102下出售时,它将在发票102下的单笔交易中登记数量。如果客户退回两件产品,它将在发票102下的表B下注册,最后,我想得到从 Return_Quantity(来自表-B)的发票102的两个Prod_1 中添加后,扣除 Sold_Quantity(来自表-A)的差异。虽然我为单个产品展示了这一点,但有超过数百种产品。

问题是我的sql查询会从发票中反复扣除,尽管它应该从 Sold_Quantity 中减去发票102的 Return_Quantity 发票102。

所以我想要的答案应该是(4 + 3)-2 = 5 。 4和3是来自表A的Sold_Quantity,2来自表-B中的Return_Quantity

任何人都可以在sql查询方面为我提供解决方案吗?

 Table-A:
    Invoice_ID | Product_ID | Sold_Quantity
         101        Prod_1          4
         101        Prod_2          5
         102        Prod_1          3

Table-B:
    Invoice_ID | Product_ID | Return_Quantity
        101         Prod_1           2
        101         Prod_2           1

2 个答案:

答案 0 :(得分:0)

您可以尝试使用内部联接并按预期获得结果:

SELECT      [Table-A].Invoide_ID, [Table-A].Product_ID, [Table-A].Sold_Quantity, 
            [Table-B].Return_Quantity, [Table-A].Sold_Quantity - [Table-B].Return_Quantity 
            AS Rem_Item
FROM        [Table-A] INNER JOIN
            [Table-B] ON [Table-A].Invoide_ID = [Table-B].Invoide_ID

剩余的项目将以Rem_Item

的形式提供

enter image description here

修改1:

  

所以我想要的答案应该是(4 + 3)-2 = 5 。 4和3是   表A和2中的Sold_Quantity来自表-B

中的Return_Quantity

由于您已整体更改了您的要求,请让我发布已编辑的查询供您参考:

SELECT        [Table-A].Product_ID, SUM([Table-A].Sold_Quantity) AS Total_Sold, 
              [Table-B].Return_Quantity, SUM([Table-A].Sold_Quantity) 
                         - [Table-B].Return_Quantity AS Rem_Item
FROM            [Table-A] INNER JOIN
                         [Table-B] ON [Table-A].Product_ID = [Table-B].Product_ID
WHERE        ([Table-A].Product_ID = N'Prod_1')
GROUP BY [Table-B].Return_Quantity, [Table-A].Product_ID

enter image description here

答案 1 :(得分:0)

希望这就是你所需要的。它只会通过匹配发票ID

进行重新定价
SELECT c1.`Invoice_ID` , c1.`Product_ID` , c1.`Sold_Quantity` , c2.Return_Quantity, Sold_Quantity - Return_Quantity AS diff 
FROM tableA c1 
LEFT JOIN tableB c2  
ON c1.Invoice_ID = c2.Invoice_ID

编辑答案。可能不是最好的一个。希望它有效

SELECT Product_ID , sold-back AS diff
FROM
(
    SELECT c1.`Product_ID` , SUM( `Sold_Quantity` ) AS sold,  
           (SELECT IFNULL(SUM(c2.Return_Quantity), 0)  FROM tableB c2 WHERE c2.Product_ID = c1.Product_ID) AS   back
    FROM `tableA` c1
    GROUP BY c1.`Product_ID`
) t