Isha Nagpal
Isha Nagpal

Reputation: 1

Copy values in column from same column with different key Postgres

I have following table in postgres

id | col1         |col2      |col3  |col4
66 | AfBLy_2_d1_1 | Sample |6798  | Day 1  
67 | AfBLy_2_d1_6 | Sample |8798 | Day 2  
66 | AfBLy_2_d1_4 | Sample |6776 | Day 7  
69 | AfBLy_2_d1_9 | Sample |6789 | Day 5  

66 | AfBLy_2_d1_1 | Sample Type  |  | Day 1
69 | AfBLy_2_d1_6 | Sample Type |  | Day 2  
66 | AfBLy_2_d1_4 | Sample Type |  | Day 7  
67 | AfBLy_2_d1_9 | Sample Type |   | Day 5  

How do i copy value of column 3 where col2= Sample to column 3 where col2 = Sample Type for corresponding col1 and id values

Upvotes: 0

Views: 53

Answers (2)

Vivek S.
Vivek S.

Reputation: 21915

update tbl t
set t.col3 = t1.col3
from (
    select id,col1,col3
    from tbl
    where col2 = 'Sample'
    ) t1
where t.col2 = 'Sample Type'
    and t.col1 = t1.col1
    and t.id = t1.id

Upvotes: 1

Gurwinder Singh
Gurwinder Singh

Reputation: 39497

You can UPDATE the table like this:

with cte as (
    select * from your_table
    where col2 = 'Sample'
)
update your_table as t1
set t1.col3 = t2.col3
from cte as t2
where t1.col2 = 'Sample Type'
and t1.col1 = t2.col1
and t1.id = t2.id;

Upvotes: 1

Related Questions