0

I have an inventory database, and i need to calculate the quantity of products after each Buy or sell operation through my stock. So, i have three tables.The equation is like so :

(QtyInital +     (BuyQuantity(IN)  - SELLQUANTITY(OUT) 

And Here is the schema of my three tables.

product(pid,name,qteInital,qteStock);
productInBuyFacture(baid,pid,qte,price,subtotal);
productInSellFacture(bsid,pid,qte,price,subtotal);

i want to calculate the current quantity of the stock via a trigger. I tried to do this via an SUB QUERYIES like so,

select ((select qteInital from product where id = 3) + 
(select qte from productInBuyFacture where pid = 3 ) - 
(select qte from productInSellFacture where pid = 3) as currentQuantity ; 
1
  • And what happened when you tried that? Commented Jan 11, 2015 at 16:15

2 Answers 2

1

My guess is that you need summation and to fix the parentheses so they balance:

select ((select coalesce(sum(qteInital), 0) from product where id = 3) + 
        (select coalesce(sum(qte), 0) from productInBuyFacture where pid = 3 ) - 
        (select coalesce(sum(qte), 0) from productInSellFacture where pid = 3)
       ) as currentQuantity ; 

The coalesce() is to prevent a problem with non-matches. A NULL in an arithmetic expression will generally cause the entire expression to return NULL.

Sign up to request clarification or add additional context in comments.

Comments

1

You can also try with explicit join:

SELECT pro.pid, pro.QtyInital, COALESCE(SUM(buy.qte), 0) AS buyqty, COALESCE(SUM(sell.qte), 0) AS sellqty
FROM product AS pro
LEFT JOIN productInBuyFacture AS buy
ON pro.pid = buy.pid
LEFT JOIN productInSellFacture AS sell
ON pro.pid = sell.pid
GROUP BY pro.pid, pro.QtyInital

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.