Click here to Skip to main content
15,891,629 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
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.

Thanx in advance


Need Urgently
Posted

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
 
Share this answer
 
v2
Comments
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!.
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	
 
Share this answer
 
Comments
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.
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
 
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