Replace one column with another based on the 3rd column of the same table in SQL

advertisements

I am having a table and for one column of table I need to replace its value wherever not null with the value in another column based on the value which it is having matched with again another column of same table.

Means say I am having table t1 with primary key c1:

  c1       c2         c3
--------------------------
1          a           null
23         b           null
2          c             1

So I want my result as:

  c1         c2            c3
------------------------------
1             a           null
23            b           null
2             c             a   ---->(means the  1 in column c3 is replaced by column c2's
                                       value whose c1's value is 1)


Here you go:

update t1 set y.c3 = x.c2
from t1 x inner join t1 y on x.c1 = y.c3;