Actually, in MS-SQL Server, there's a 4th way and it's very, very fast...--===== You MUST have a clustered index on the table that looks like this in order for this to work. -- If you can't change the indexes on yourtable, you'll need to copy to a temp table that you can add the index to, -- do the running total update on the temp, and then update yourtable from that. -- Even that will still be faster than anything you could do with a loop or a cursor. CREATE CLUSTERED INDEX IXC_yourtable_Item_Date ON yourtable (Item,Date)--===== Declare some local working variables with some obvious namesDECLARE @PrevAvailable INTDECLARE @PrevItem VARCHAR(10)DECLARE @PrevATP INT --Never assigned but necessary to work correctly--===== Preset the key working variables SET @PrevAvailable = 0 SET @PrevItem = ''--===== Create the grouped running balance in the Available column and the balance brought forward in the ATP column UPDATE dbo.yourtable WITH (TABLOCK) --Tablock guarantees the required exclusive use SET @PrevAtp = ATP = CASE WHEN @PrevItem = Item THEN @PrevAvailable ELSE 0 END, @PrevAvailable = Available = CASE WHEN @PrevItem = Item THEN @PrevAvailable+Stock-Demand ELSE Stock-Demand END, @PrevItem = Item
[EDIT] One other thing... it assumes that the Date column is a DATETIME column. Also, I haven't tested it with dupe dates for any given item but it will likely still work correctly because this is nothing more the RBAR on steroids.--Jeff Moden