在mysql查询中添加和减去sum列

时间:2013-09-12 05:58:05

标签: mysql sql

我有这个SQL来检索所有项目

SELECT A.item_code,A.description,A.uom, A.open_stock, B.recd_total, C.issue_qty
FROM chem_master as A
LEFT JOIN ( SELECT item_code, sum(recd_qty) as recd_total
from chem_reciepts GROUP BY item_code) as B on A.item_code=B.item_code
LEFT JOIN(SELECT item_code, sum(iss_qty) as issue_qty
from chem_issue GROUP BY item_code) as C on A.item_code=C.item_codeand 

返回的数据是

Item_code Description                      unit op.stock recd_total issue_qty

25139     ALUMINIUM OXIDE ACTIVE NEUTRAL   GM       0         0          0
54006     L-ASCORBIC ACID                  GM       0         0          0
AC001     ACETIC ACID GLACIAL              LTR      0         14         2
AC002     ACETONE AR                       LTR      0         0          0
AC005     ACACIA POWDER                    GM       0         0          0

我只想要那些open_stock + recd_total - issue_qty = 0

的记录

如何修改sql?

3 个答案:

答案 0 :(得分:2)

您可以使用您提到的条件添加having(在查询结束时)。
如下所示:

HAVING op.stock+recd_total-issue_qty=0

答案 1 :(得分:0)

试试这个

SELECT q.*, (q.stock+(q.recd_total-q.issue_qty)) as resultant FROM (
SELECT A.item_code,A.description,A.uom, A.open_stock, B.recd_total, C.issue_qty
FROM chem_master as A
LEFT JOIN ( SELECT item_code, sum(recd_qty) as recd_total
from chem_reciepts GROUP BY item_code) as B on A.item_code=B.item_code
LEFT JOIN(SELECT item_code, sum(iss_qty) as issue_qty
from chem_issue GROUP BY item_code) as C on A.item_code=C.item_codeand
) q  HAVING q.resultant =0

答案 2 :(得分:0)

使用以下查询

SELECT A.item_code,A.description,A.uom, A.open_stock, B.recd_total, C.issue_qty
FROM chem_master as A
LEFT JOIN ( SELECT item_code, sum(recd_qty) as recd_total
from chem_reciepts GROUP BY item_code) as B on A.item_code=B.item_code
LEFT JOIN(SELECT item_code, sum(iss_qty) as issue_qty
from chem_issue GROUP BY item_code) as C on A.item_code=C.item_codeand 
having op.stock+recd_total-issue_qty = 0;