15,939,065 members
See more:
Hi guys,

I have a table like this :

Id Name Code
1 A Null
2 B 12
3 C Null
4 D Null
5 E Null
6 F 45
7 G 67
8 H Null
9 I Null
10 J 8

I want a result like this
Id Name Code
1 A 0
2 B 12
3 C 12
4 D 12
5 E 12
6 F 45
7 G 67
8 H 67
9 I 67
10 J 8

That means I need to update CODE with previous value if not than 0 like row 1.

Need Urgently
Posted

## Solution 4

Hello. Try this code. Replace @a with your table name.

SQL
declare @b table
(
id int,
newcode int
)

declare @prev int

insert into @b(id,newcode) select  id,code from @a
order by id desc

set @prev = 0

update @b
set @prev=ISNULL(newcode,@prev),
newcode=@prev
from @b

select a.id,a.name,b.newcode
from @a a inner join @b b on a.id = b.id

v2
JigneshSurati 30-Jan-20 4:48am
Somehow came to this blog.

My problem was difference like calculate Open, +, -, Close.

By joining with LEFT JOIN, got current row & previous row, then calculated with setting first into variables and then updating physical records.

This solved my problem!

Even "LAG" and "Recursive query with CTE" failed.

But this worked for me!.

## Solution 2

Does this work?
SELECT a.Id, a.Name, a.Code, (
SELECT SUM(b.Code)
FROM [table] b
WHERE b.Id <= a.Id
)
FROM [table] a
ORDER BY a.Id

rakesh@bbspl.com 17-Oct-13 0:32am
Thanks for the reply, but it will not fulfill the requirement. This only gives the SUM from least to upper.
I need to overwrite null values from last existing value.

## Solution 3

SQL
Select  Id
, Name
, Code
, (Select Case When a.code <> 0 Then A.Code Else Sum(b.Code) End
From TableName as b
Where b.Id < a.Id) AS Code1
From TableName As a