Skip to content
Advertisement

SQL – Subtracting a depleting value from rows

I have a situation where I need to take a “quantity consumed” from one table, and apply it against a second table that has 1 or more rows that are “pooled lots” of quantities. I’m not sure how to describe it better, here’s what I mean from a table perspective:

I need a resulting rowset from a SQL query that would look like:

So, Pool_Consumption.QuantityConsumed needs to be a “depleting value” subtracted over the rows from Pooled_Lots where Pool_Consumption.PoolId = Pooled_Lots.Pool. I can’t figure out how you would state a query that says:

  • If not on the last row, AmtConsumedFromLot = Quantity – QuantityConsumed if QuantityConsumed < Quantity, else Quantity
  • If more rows, QuantityConsumed = QuantityConsumed – Quantity
  • Loop until last row
  • If last row, AmtConsumedFromLot = QuantityConsumed

Assume Id is a primary key, and the target DB is SQL 2005.

Edit: Since people are proclaiming I am “not giving enough information, please close this” Here is more: There is NO set lot that the Pool_Consumption draws from, it needs to draw from all lots where Pool_Consumption.PoolId = Pooled_Lots.Pool, until QuantityConsumed is either completely depleted or I am subtracting against the last subset of Pooled_Lots rows where Pool_Consumption.PoolId = Pooled_Lots.Pool

I don’t know how more to explain this. This is not a homework question, this is not a made-up “thought exercise”. I need help trying to figure out how to properly subtract QuantityConsumed against multiple rows!

Advertisement

Answer

Left as an exercise to the OP: Figuring out the correct results given the sample data and summarizing the results of the following query:

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