I have a table as below:
id code value total
==========================
1 A/01 5
2 A/01 8
3 A/01 6
1 A/02 8
2 A/02 3
3 A/02 7
1 A/03 6
2 A/03 9
3 A/03 2
I want to update the total with value of same row + previous row's. I declared a variable as below and update the table:
DECLARE @sum int
SET @sum = 0
UPDATE @table set total = @sum, @sum = @sum + value
It works perfect if I select for the first code:
SELECT * FROM table WHERE code='A/01'
id code value total
==========================
1 A/01 5 5
2 A/01 8 13
3 A/01 6 19
But if I select the whole table, then it does this:
id code value total
==========================
1 A/01 5 5
2 A/01 8 13
3 A/01 6 19
1 A/02 8 27
2 A/02 3 30
3 A/02 7 37
1 A/03 6 43
2 A/03 9 52
3 A/03 2 54
How can I update the table as I explained so it resets adding values when value in "code" column changes?? Please help, I need the following result, Thanks!
id code value total
==========================
1 A/01 5 5
2 A/01 8 13
3 A/01 6 19
1 A/02 8 8
2 A/02 3 11
3 A/02 7 18
1 A/03 6 6
2 A/03 9 15
3 A/03 2 17