Skip to content
Advertisement

How to distribute stock quantity from a single cell to different aging brackets based on the the aging brackets quantities?

We have a table with item codes and current stock quantity and quantities in aging brackets whenever they were received (1-90, 91-120, etc) as follows:

Data

I need to distribute the STOCK_AS_ON_DATE quantity in the age brackets until no balance quantity is left.

Example:

Item A’s STOCK_AS_ON_DATE is 40377, in A1TO90 column we can see that 4000 quantities were received, in A91TO120, 4000 quantities were received, in A121TO270, 13000 quantities were received, we want to distribute the STOCK_AS_ON_DATE quantity in such a way in the other aging fields until the total of all the aging fields equals STOCK_AS_ON_DATE. In this item’s case, when we reach column A631TO720, 1377 quantity balance is left out of the 40377. If any aging bracket value is 0, we have to leave it as it is and move forward.

Example

Below is the Oracle query to create a sample table and data:

We have tried using the CASE statement but as we move further to other columns it’s becoming complicated.

There must be some other way which we are not aware of. Please suggest a simpler way to achieve our results. Thanks in advance.

Advertisement

Answer

A brute-force approach might be to use least() to decide whether to use the column quantity or the remainder from adding up all the columns to the left; with greatest() to stop any negative values. Something like:

which is ugly and doesn’t scale very well, but isn’t really complicated per se. (This gives zero for the columns after you’ve exhausted the stock; your example had null for the final column for item A, but not sure if it matters; making it null is just a bit more complicated.)

If you want the total column you showed – again not sure you really do – you can use that as a CTE or inline view:

db<>fiddle

If you are on 11g then you could unpivot your columns to rows:

then perform a similar calculation using a running total:

and pivot that back to columns:

db<>fiddle

If you’re on 10g then you could manually unpivot and pivot but it probably isn’t worth the complication over the brute-force approach.

Both approaches give:

If you were on 12c or above you could look at match_recognize(), but you seem to be on either 10g or 11g.

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