是否有任何mysql内置函数,通过它我们可以减去不同表的总和

时间:2019-01-09 11:40:22

标签: mysql join

我有两个桌子。 tblPurchaseDetails为

SNO       ParticularID       Particular        Qty         Date
1            1                Apple             10           2019-01-01
2            2                Orange            20           2019-01-01
3            3                Papaya            10           2019-01-01
4            2                Orange            30           2019-01-04
5            1                Apple             50           2019-01-05  

另一个表tblStockout的详细信息为

SNO       ParticularID       Particular        Qty         Date
1            1                Apple             10           2019-01-02
2            2                Orange            20           2019-01-02
4            2                Orange            10           2019-01-05
5            1                Apple             20           2019-01-06              

现在我想获得当前可用的水果库存,应该看起来像

ParticularID       Particular        Qty       
   1                Apple             30          
   2                Orange            20          
   3                Papaya            10   

如何使用mysql内置函数获取此信息? 谢谢。

编辑:

我尝试过

select purchasedetails.Particular, 
        sum(purchasedetails.qty)-sum(stockoutdetails.Qty) 
from purchasedetails 
    left join stockoutdetails on purchasedetails.particular=stockoutdetails.particular 
GROUP by purchasedetails.particular

1 个答案:

答案 0 :(得分:2)

此查询将为您提供所需的结果。它从采购表和缺货表中创建了两个数量总和的派生表,并采用差值来获取现有数量:

SELECT p.ParticularID, p.Particular, COALESCE(p.Qty, 0) - COALESCE(s.Qty, 0) AS Qty
FROM (SELECT ParticularID, Particular, SUM(Qty) AS Qty
      FROM tblPurchaseDetails
      GROUP BY ParticularID, Particular) p
LEFT JOIN (SELECT ParticularID, SUM(Qty) AS Qty
           FROM tblStockoutdetails
           GROUP BY ParticularID) s ON s.ParticularID = p.ParticularID
ORDER BY p.ParticularID

输出

ParticularID    Particular  Qty
1               Apple       30
2               Orange      20
3               Papaya      10

Demo on dbfiddle