• This is similar to Itzik Ben-Gan's Depleting Quantities challenge:

    http://sqlmag.com/t-sql/t-sql-challenges-replenishing-and-depleting-quantities

    It can be solved with a QU as Alan.B has suggested.

    However I should warn you that there are those that are not believers in that method. IBG happens to be one of them. When I proposed using a QU for his Depleting Quantities challenge, he explained to me why. And I have seen cases that will break a QU.

    I'm fence-sitting on that solution for the time being (even though many have seen me use it and write about it in the past).

    I did propose an alternate solution to Mr. Ben-Gan that did work and I haven't heard that he's come up with a better one (he'd probably have written about it by now if he did). It consists of a set-based while loop.

    If you're happy with the QU solution Alan provided then use it. If you have concerns about it, let me know and I'll try to dig up what I did for IBG.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St