Click here to Skip to main content
15,886,639 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Task 1
Input		           Out Put
Current	Previous	
1001	Null	
2331	7808	           -6807
2312	8965	           -6634
3213	5557	           -3245
8768	3453	            -240
8857	6577	            2191
Null	6778	            2079




Note : First Row - Second row in second column

[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 13-May-15 20:40pm
v2
Comments
Thanks7872 14-May-15 2:20am    
Nothing is clear. Even title doesn't says anything regarding your issue.
Mycroft Holmes 14-May-15 2:21am    
There is not enough detail to help, are there 2 or 3 or 5 columns. You may want to look at ROW_NUMBER() to get a sequential row ID so you can locate the previous row to do any (obscure) calcs.
_Asif_ 14-May-15 2:22am    
This is not a good way to ask question. Please do understand, we can't read your screen, your hard disk, your mind!

There is no way we can understand "Note: First Row - Second row in second column" meant.

Please use Improve Question option and add more details.

In addition to Mycroft Halmes post you may required this result.

SQL
DECLARE @Tbl TABLE(ID INT , Value1 INT ,value2 INT,Result INT)
 
INSERT @Tbl (ID,Value1,value2)
SELECT 1, 1001,NULL
UNION SELECT 2,2331,    7808
UNION SELECT 3,2312,    8965         
UNION SELECT 4,3213,    5557          
UNION SELECT 5,8768,    3453           
UNION SELECT 6,8857,    6577         
UNION SELECT 7,NULL,   6778    

Declare @ID as INT
Declare @Value1 as INT
Declare @Value2 as INT
Declare @result as INT
Declare @tmp as INT=NULL

Declare MY_data CURSOR FOR
 
Select ID,Value1,Value2 from  @Tbl 
 
OPEN MY_data
    FETCH NEXT FROM MY_data INTO @ID,@Value1,@value2
        WHILE @@FETCH_STATUS = 0
        BEGIN
			update @Tbl 
			Set result=@tmp-@Value2
			WHere Id=@ID
			
			set @tmp=@value1

	FETCH NEXT FROM MY_data INTO @ID, @value1,@value2
        END
    CLOSE MY_data
DEALLOCATE MY_data

select * from @Tbl
 
Share this answer
 
v2
Try this, you need a row identifier, that is where you may need to use ROW_NUMBER().

SQL
DECLARE @Tbl TABLE(ID INT , Value1 INT ,value2 INT)

INSERT @Tbl
SELECT 1, 1001,0
UNION SELECT 2,2331,	7808
UNION SELECT 3,2312,	8965         
UNION SELECT 4,3213,	5557          
UNION SELECT 5,8768,	3453           
UNION SELECT 6,8857,	6577         
UNION SELECT 7,0,	6778        


SELECT *, t.value1 - t2.Value2 Result
FROM  @Tbl AS t
LEFT JOIN @Tbl AS t2 ON t.ID = t2.ID - 1
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900