question

sqlnewb avatar image
sqlnewb asked

Update to a Column

I have a table with 3 columns. I am trying to update one of the columns with adding ColA+ColB of row 1 and putting the value in ColA of row2. ColA is already pre-populated with ZEROS Below is an example This is what I have now: ID ColA ColB 1 0 0 2 0 5 3 0 7 4 0 3 5 0 4 This is what i want: ID ColA ColB 1 0 0 2 0 5 3 5 7 4 12 3 5 15 4 This is a query I am trying to get to work but having issues: update t1 set t1.ColA = (select(sum(t1.ColB) ` `from tableA t1 where t1.id < t1.id)) Any Suggestions would be helpful
t-sqlupdate
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Kev Riley avatar image
Kev Riley answered
declare @yourtable table (id int, cola int, colb int) insert into @yourtable select 1,0,0 insert into @yourtable select 2,0,5 insert into @yourtable select 3,0,7 insert into @yourtable select 4,0,3 insert into @yourtable select 5,0,4 update t1 set cola = isnull((select sum(colb) from @yourtable t2 where t2.id < t1.id),0) from @yourtable t1 select * from @yourtable
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.