You'll need a table of transactions with a transaction date, cost, qty, product ID, and a sold field.
Each time that your sales invoice gains a line item, deduct the qty from Oldest record for that product where the sold field is less than the Qty. Increment the sold field of that record.
This is just rough outline as there are many different implementation possibilities.
Part of that is physically pulling the FI item to sell/send/give (FO). That is another "storage/retrieval" solution that is (mostly) outside a database storage of the pointer to that item.
But are you asking what about the cost difference of these items (averaging the price) or are you asking about an "expiration date" scenario as for perishable items?