根据条件替换null

3df52oht  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(263)

我有一个包含许多列的表(但这里只发布col1、col2、col3以简化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)

我想填补 null values of source _idvalues 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)
l2osamch

l2osamch1#

这看起来像一个 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

相关问题