the code is documented explaining each step. I use the same principle of using the stocktake date as a starting point for your quantity on hand and summing from there. The only issue is having an accurate date and time since a stocktake taken at the start of the day may vary from one at the end because movements might have occurred during the day.
for example you table might look like
tblItems
itemPK
itemName
tblStockMovement
MovementPK
ItemFK
trantype (e.g. issued, received, stocktake)
trandateT
Qty
simplistically your query might look something like
Code:
SELECT tblStockMovement.itemFK, sum(qty) as onHand
from tblStockMovement INNER JOIN (SELECT itemFK, Max(trandateT) AS LastST FROM tblStockMovement WHERE trantype='StockTake' GROUP BY itemFK) AS ST ON tblStock.itemFK=ST.itemFK
WHERE tblStock.trandateT>=ST.LastST
GROUP BY tblStockMovement.itemFK
this bit is finding the last stocktake
Code:
(SELECT itemFK, Max(trandateT) AS LastST FROM tblStockMovement WHERE trantype='StockTake' GROUP BY itemFK)
whilst this bit limits the records to those movements that are on or after the stocktake datetime
Code:
WHERE tblStock.trandateT>=ST.LastST