Replacing null based on a condition

给你一囗甜甜゛ 提交于 2021-02-11 04:23:24

问题


I am having a table with many columns (but posting only col1, col2, col3 here for simplified post):

id    col1       col2            col3    source_id
a1    765.3      23-Apr-08       cat     a5
a2    3298.3     (null)          dog     a4
a3    8762.1     27-Nov-10       rat     a8
a4    (null)     (null)          (null) (null)      
a5    (null)     (null)          (null)  a6
a6    (null)     (null)          (null)  (null)

I want to fill null values of source _id with values from id. For example, source_id a5 row has null which has to replaced with id a1 values, subsequently, source_id a6 row having null to be replaced with a5 row

Output:

id    col1       col2            col3   source_id
a1    765.3      23-Apr-08       cat    a5
a2    3298.3     (null)          dog    a4
a3    8762.1     27-Nov-10       rat    a8
a4    3298.3     (null)          dog   (null)       
a5    765.3      23-Apr-08       cat    a6
a6    765.3      23-Apr-08       cat  (null)

回答1:


This looks like a left join and conditional logic:

select 
    t.id,
    coalesce(t.col1, t1.col1) col1,
    coalesce(t.col2, t1.col2) col2,
    coalesce(t.col3, t1.col3) col3,
    t.source_id
from mytable t
left join mytable t1 on t1.id = t.source_id


来源:https://stackoverflow.com/questions/62061075/replacing-null-based-on-a-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!