使用不同的键Postgres

时间:2017-01-17 05:21:36

标签: sql postgresql

我在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  

如何将第3列的值复制到第3列,其中col2 = Sample为第3列,其中col2 =相应col1和id值的样本类型

2 个答案:

答案 0 :(得分:1)

您可以像这样更新表格:

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;

答案 1 :(得分:1)

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