Skip to content
Advertisement

Oracle SQL Query for Distributing Quantity

I have one table called INVENTORY which has data:

Let’s say, I have a request to fetch the quantity of 20 from these LOTs. As per the table, I have a total quantity available 24 (10 + 14). So I have enough quantity. I can take 10 Quantities from A1 and 10 from A2. But Instead, I have to look at the LOT_EXPIRY_DATE. Since A2 is expiring first, I shall take 14 quantities from A2 and then the rest of the quantities i.e. 6 from A1.

So below query works just fine:

Result:

But if the requested quantity is 13, then the result is

Expected Result:

Is it possible to have a single query that can work well with both the quantities?

Need help with that query.

Advertisement

Answer

You want a cumulative sum and them some comparison logic:

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement