根据条件替换null

时间:2020-05-28 09:14:00

标签: sql oracle join select left-join

我有一个包含很多列的表(但这里只发布了col1,col2,col3以简化发布):

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)

我想用null values of source _id来填充values from id。 例如,source_id a5 row has null必须替换为id a1 values,随后source_id a6 row having null必须替换为a5 row

输出:

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 个答案:

答案 0 :(得分:0)

这看起来像是left join和条件逻辑:

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