0

I'm somehow not contented with my query statement and am wondering if there are other better way to do this:

SELECT product.product, 
 COALESCE((SELECT SUM(qty) FROM stocktrxn 
 INNER JOIN stock on stock.tra_no = stocktrxn.tra_no 
 WHERE product_no = s1.product_no and stock.is_out = false) - 
 (SELECT SUM(qty) FROM stocktrxn 
 INNER JOIN stock on stock.tra_no = stocktrxn.tra_no 
 WHERE product_no = s1.product_no and stock.is_out = true), 0)
 as qty
FROM stocktrxn s1
RIGHT JOIN product on product.id = s1.product_no
GROUP BY product ASC;

1 Answer 1

1

I think you just want conditional aggregation. Something like this:

SELECT p.product,
       (SUM(CASE WHEN s.is_out = false THEN qty ELSE 0 END) -
        SUM(CASE WHEN s.is_out = true THEN qty ELSE 0 END) -
       ) as qty
FROM product LEFT JOIN
     stocktrxn st
     ON p.id = st.product_no LEFT JOIN
     stock s
     ON s.tra_no = st.tra_n
GROUP BY p.product ASC;
Sign up to request clarification or add additional context in comments.

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.