SQL 也给出了 table 列的派生名称
SQL that also gives the table names from which the columns were derived
下面的 SQL 代码还需要获取从中提取列的 table 名称,以维护沿袭以供稍后分析。我需要建议来实施这样的 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 列应该提供 table 名称,前 3 列是从中提取的。
你可以这样做:
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
我并不是说它很优雅。相反,在单个查询中组合数据和元数据不可避免地会导致笨拙。
下面的 SQL 代码还需要获取从中提取列的 table 名称,以维护沿袭以供稍后分析。我需要建议来实施这样的 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 列应该提供 table 名称,前 3 列是从中提取的。
你可以这样做:
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
我并不是说它很优雅。相反,在单个查询中组合数据和元数据不可避免地会导致笨拙。