How to calculate quantity on hand for every lot (mysql)

grimdbx :

This is the transaction details table

I am trying to design a Mysql inventory database. I consider every type: 1 row a product lot (batch).

The type column has 1 for IN and 0 for OUT for each transaction. detail_id is referencing the id column.

How can I get this result:

 id   item  sum(quantity)
  1     1         3            [10-(5+2)]
  4     1         0            (5-5)
  6     2         20            20
Sebastian Brosch :

You can use this:

SELECT 
  lots.id,
  MIN(lots.item) AS item,
  MIN(lots.quantity) - IFNULL(SUM(details.quantity), 0) AS quantity 
FROM (
  SELECT id, item, quantity 
  FROM details
  WHERE type = 1
) lots LEFT JOIN details ON lots.id = details.detail_id 
GROUP BY lots.id
ORDER BY lots.id

demo on dbfiddle.uk

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=401687&siteId=1