Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Declare @counter int, @unit char(4),@unit2 char(4),@days int, @totalDays int
- --initialize to 0
- Select @days=0, @totalDays=0
- /*Start at the current row*/
- SELECT @counter = (SELECT max(rownum) FROM #mixer)
- While @counter > 0
- begin
- /*initialize unit and days variables to first value*/
- SET @unit =(SELECT unit FROM #mixer WHERE rownum = @counter),
- @unit2 =(SELECT unit FROM #mixer WHERE rownum = @counter-1),
- @days= (SELECT days FROM #mixer WHERE rownum = @counter)
- /*compare to see if the current cell is the same as the previous one*/
- IF compare(@unit,@unit2)=0
- begin
- /*If they are equal increment total variable by # of days*/
- SET @totalDays = @totalDays + @days
- /*Move up one row*/
- set @counter= @counter-1
- end
- ELSE /*We are done..previous row had a different group*/
- /*Persistance of values*/
- INSERT INTO #totals
- SELECT distinct unique_id,
- another_id,
- @unit,
- @days-1,
- @totalDays
- FROM #mixer
- /*needs to be reset to avoid infinite loop*/
- SET @counter = 0, @totalDays = 0
- end
- /*Get rid of rows we just used in #mixer*/
- DELETE #mixer WHERE unique_id = @unique_id
Add Comment
Please, Sign In to add comment