下面的 SQL 代碼還需要獲取從中提取列的表名,以維護一個譜系以供稍后分析。我需要建議來實作這樣的 SQL:
select
COALESCE(t1.col1,t2.col1,t3.col1) new_col1,
COALESCE(t1.col2,t2.col2,t3.col2) new_col2,
COALESCE(t1.col3,t2.col3,t3.col3) new_col3
from
table1 t1
left join table2 t2 on t1.id = t2.id
left join table3 t3 on t1.id = t3.id
結果,我需要得到一個類似于這樣的輸出:
new_col1 new_col2 new_col3 new_col1_source new_col2_source new_col3_source
val1 val2 val3 table1 table1 table3
在上面的結果中,最后 3 列應提供從中提取前 3 列的表名。
uj5u.com熱心網友回復:
你可以這樣做:
select
COALESCE(t1.col1,t2.col1,t3.col1) new_col1,
COALESCE(t1.col2,t2.col2,t3.col2) new_col2,
COALESCE(t1.col3,t2.col3,t3.col3) new_col3,
case when t1.col1 is not null then 'table1'
when t2.col1 is not null then 'table2'
when t3.col1 is not null then 'table3' end as new_col1_source,
case when t1.col2 is not null then 'table1'
when t2.col2 is not null then 'table2'
when t3.col2 is not null then 'table3' end as new_col2_source,
case when t1.col3 is not null then 'table1'
when t2.col3 is not null then 'table2'
when t3.col3 is not null then 'table3' end as new_col3_source
from
table1 t1
left join table2 t2 on t1.id = t2.id
left join table3 t3 on t1.id = t3.id
我不是說它很優雅。相反,在單個查詢中組合資料和元資料不可避免地會導致笨拙。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/352419.html
