I assume the products are manufactured by your company rather than purchased
from external suppliers, with each batch of each product having a manufacture
date. If so, tables such as the following can be used:
Products
….ProductID (primary key)
….Product
Batches
….ProductID (foreign key)
….ManufactureDate
….Quantity
The primary key of the Batches table would be a composite one made up of the
ProductID and ManufactureDate columns.
If you also have tables recording sales of products, e.g.
Sales
….SaleID (primary key)
….CustomerID (foreign key)
….SaleDate
SaleDetails
….SaleID (foreign key)
….ProductID (foreign key)
….ManufactureDate (foreign key)
….Quantity
The primary key of this table is a composite one of SaleID, ProductID and
ManufactureDate if a sale can include the same product from more than one
batch, or SaleID and ProductID if from only one batch. Note that ProductID
and ManufactureDate constitute a composite foreign key referencing the
composite primary key of Batches.
Customers
….CustomerID (primary key)
….Customer
The current stock in hand per batch can now be computed with a query which
subtracts the sum of all sales per batch from the sum of the quantity
manufactured per batch:
SELECT Product, ManufactureDate,
SUM(Batches.Quantity) - SUM(SaleDetails.Quantity) AS StockInHand
FROM Products, Batches, SaleDetails
WHERE Batches.ProductID = Products.ProductID
AND SaleDetails.ProductID = Batches.ProductID
AND SaleDetails.ManufactureDate = Batches.ManufactureDate
GROUP BY Product, ManufactureDate;
If you are not discriminating between batches in sales then the stock in hand
per product can be computed by a similar query which subtracts the sum of all
sales per product from the sum of the quantity manufactured per product:
SELECT Product,
SUM(Batches.Quantity) - SUM(SaleDetails.Quantity) AS StockInHand
FROM Products, Batches, SaleDetails
WHERE Batches.ProductID = Products.ProductID
AND SaleDetails.ProductID = Batches.ProductID
GROUP BY Product;
Ken Sheridan
Stafford, England