Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Rolling value to next rows

Author  Topic 

skbn136
Starting Member

1 Post

Posted - 2007-01-13 : 21:52:34
Hi All,

Please help me in solving this problem. The scenario is mentioned downunder:

Table A

Item ATP Date Stock Demand Available
A 0 01/07 100 70 30
A 30 08/07 30 40 20

ATP is 0 and the formula to calculate available is ((ATP+STOCK) - Demand)). For the first record Available is 30 ((0+100)-70). I want the value of Available to be copied to ATP of next record. Is it possible in SQL.

Regards

skbn

snSQL
Master Smack Fu Yak Hacker

1837 Posts

Posted - 2007-01-15 : 13:11:06
Yes, it is possible. How do you identify the "next record"?
Go to Top of Page

tmitch
Yak Posting Veteran

60 Posts

Posted - 2007-01-16 : 20:00:59
One of three ways to do this:

-- If the data is such that you can identify the next record, a single SQL statement would probably do it.
-- You could pull the records into a temp table and iterate though the records with a WHILE loop
-- If you're really daring, you can use a cursor - but I recommend this only as a last resort.

Hope this helps.
Tim
Go to Top of Page

Jeff Moden
Aged Yak Warrior

652 Posts

Posted - 2007-01-18 : 09:15:44
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 names
DECLARE @PrevAvailable INT
DECLARE @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
Go to Top of Page
   

- Advertisement -