我有一个包含很多列的表(但这里只发布了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)
答案 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