Avg cost per desk is $35,000
Gal 1 money to company = $38,000
Gal 2 = $35,350
Gal 3 = $33,100
Gal 4 = $1,100
Gal 5 = $1,000
Read Gal 1. Since she brought in > $35,000, add 1 to number of desks covered.
Read Gal 2. Since she brought in > $35,000, add 1 to number of desks covered. (Total desks covered now = 2)
Read Gal 3. Since she brought in < $35,000, go to last Gal in list (Gal 5) and add the money she brought in ($1,000) to the money brought in by Gal 3 ($33,100) and get a total of $34,100. Since $34,100 is less than $35,000, go to the next lowest (Gal 4) and add her $1,100 to the $34,100 total and get a total of $35,100. Since this is > $35,000, add 1 to the number of desks covered (Total desks covered now = 3). If there were more, Let's say there were 10 and Gals 1 through Gal 3 had the same numbers and Gals 4 and 5 now became Gals 9 and 10, but and had the same amount of money to company, after the above process we would go back up to the person who is now Gal 4 and read her money. Since it is lower than Gal 3, she also doesn't cover a desk. So we go to the bottom of the list. But we have already used 9 and 10, so we go to 8. Add her money to the money from Gal 4. If it is > $35,000, add 1 to the covered desks and go up to gal 5 and repeat. If the total is still less than $35,000, go to Gal 7 and add her money and run the check.
I'm doing this with two loops. The inner loop runs as long as the total is less than the desk cost. The addition to the number of desks covered is done in the outer loop. So, if the first record covers the cost of a desk, the inner loop doesn't run and 1 is added to the total. When the outer loop hits a record that doesn't cover a desk, the inner loop runs and picks up records starting at the bottom and adds to the money until the total money goes over the desk cost.
Both loops keep track of where they are, and when they meet, they stop and spit out the results.
Here are the loops:
WHILE @csrPos <= @FilRecNo AND @csrPos <= @Dsks
BEGIN
FETCH ABSOLUTE @RcdNo FROM csrPorCoRevRnk
INTO @CoNum, @OffNum, @OffNam, @AssocID, @Assoc, @PoCoRev
SET @PoCoRevHld = @PoCoRev
WHILE @PoCoRevHld < @AvgDskCst AND @RcdNo < @FilRecNo
BEGIN
FETCH ABSOLUTE @FilRecNo FROM csrPorCoRevRnk
INTO @CoNum, @OffNum, @OffNam, @AssocID, @Assoc, @PoCoRev
SET @PoCoRevHld = @PoCoRevHld + @PoCoRev
SET @FilRecNo = @FilRecNo - 1
END
IF @PoCoRevHld >= @AvgDskCst SET @PdFrDsks = @PdFrDsks + 1
--PRINT CAST(@PdFrDsks AS VARCHAR) + ' desks are paid for with Portion Co Rev of ' + CAST(@PoCoRevHld AS VARCHAR) + ' and ' + CAST(@PoCoRev AS VARCHAR) + ' ' + CAST((@PoCoRevHld - @PoCoRev) AS VARCHAR)
SET @csrPos = @csrPos + 1
SET @PoCoRevHld = 0
SET @RcdNo = @csrPos
END
PoCoRev and PoCoRevHld are the money
FilRecNo is the number of agents