【问题标题】:SQL that also gives the table names from which the columns were derivedSQL 也给出了列的派生表名
【发布时间】:2021-12-20 22:11:46
【问题描述】:

下面的 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 列的表名。

【问题讨论】:

    标签: sql oracle join


    【解决方案1】:

    你可以这样做:

    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
    

    我并不是说它很优雅。相反,在单个查询中组合数据和元数据不可避免地会导致笨拙。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      相关资源
      最近更新 更多