mardi 4 août 2015

Mysql Conditional sum

Here is my 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_receipts 
                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_code 
HAVING (open_stock+recd_total-issue_qty) IS NULL OR (open_stock+recd_total-issue_qty)=0

Here, table chem_receipts & chem_issue do not have all the matching records in chem_master. Also, there may be multiple matching records.

I want to show items where stock is 0. There are 300 items in chem_master. But only 15 records in chem_receipts since we had additional purchase only in these 15 items. There are 100 records in chem_issue.

Now in the returned query against items where no additional purchase is made is shown as NULL & the same is the case where an item is never issued.

I understand that adding records of all the items with '0' in quantity in issue and receipt table will solve the issue. But that will not be a better method.

How can I improve this query?

Aucun commentaire:

Enregistrer un commentaire