• While I don't have time at the moment to craft a full-blown solution for you, I might have a couple of ideas to get you started.

    I don't think you're going to be able to do this without some kind of a loop. So you might want to start with something like this:

    SELECT TransactionNumber, SkuNumber, QuantitySold=SUM(QuantitySold)

    ,ProductAllocated=0

    INTO #Temp

    FROM SalesTransactionDetail

    GROUP BY TransactionNumber, SkuNumber;

    Then go into a set-based WHILE loop, which checks for each EventID (one at a time) whether each transaction qualifies based on QuantitySold - ProductAllocated (to an event). You would then need to update ProductAllocated (in #Temp) for each SKU that qualified for an event. Finally loop back and check the next event.

    The "set-based" nature of the WHILE loop is to indicate you can process all transactions that remain with unallocated products on each pass through the loop.

    Easier said than done (probably).


    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