【问题标题】:Combining 2 data sets with the same columns, but different values将 2 个具有相同列但值不同的数据集组合在一起
【发布时间】:2019-02-13 17:51:43
【问题描述】:

我有 2 个数据集:Table1 和 Table2

Table1 如下所示:

Individual_ID    Code1    Code 2  
1234             1        2  
2345             NULL     NULL  

Table2 如下所示:

Individual_ID    Code1    Code 2  
1234             NULL     NULL   
2345             1        2  

我希望合并后的结果如下所示:

Individual_ID    Code1    Code 2  
1234             1        2  
2345             1        2  

基本上我要做的是将具有相同 ID 列表和相同列标题的多个表放在一起,但与 ID 关联的列中的数据在我尝试的每个表中都不同聚在一起

【问题讨论】:

    标签: sql join union


    【解决方案1】:

    你可以使用UNION ALL

    SELECT Individual_ID, Code1, Code2  
    FROM table t1
    WHERE Code1 IS NOT NULL AND Code2 IS NOT NULL
    UNION ALL
    SELECT Individual_ID, Code1, Code2  
    FROM table t2
    WHERE Code1 IS NOT NULL AND Code2 IS NOT NULL;
    

    【讨论】:

    • 这太好了,有没有办法让它返回一个实例,其中一个值恰好为空?例如:也许 table1 的 individual_ID 值为 null 和 2,而 Table2 的 individual_id 相同,但为 Null 和 null。我希望在决赛桌中的值是 Individual_id null 和 2 有意义吗?
    • @Ciccotelli412。 . .这就是查询的作用。
    【解决方案2】:

    我想你想要joincoalesce()

    select t1.Individual_ID, coalesce(t1.code1, t2.code1) as code1,
           coalesce(t1.code2, t2.code2) as code2
    from table1 t1 join
         table2 t2
         on t1.Individual_ID = t2.Individual_ID;
    

    【讨论】:

    • 太棒了!有没有办法用总共5张桌子做到这一点?完全相同的场景
    • 继续模式。 . .更多joins,更多参数coalesce()。如果您需要更多指导,请提出另一个问题。
    【解决方案3】:

    一种选择是使用coalesce

    select t1.Individual_ID, 
           coalesce(t1.code1,t2.code1) as code1, 
           coalesce(t1.code2,t2.code2) as code2
      from table1 t1 
      join table2 t2 on t1.Individual_ID = t2.Individual_ID
    

    编辑:您可以为五个具有相同场景的表执行此操作

    select t1.Individual_ID, 
           coalesce(t1.code1,t2.code1,t3.code1,t4.code1,t5.code1) as code1, 
           coalesce(t1.code2,t2.code2,t3.code2,t4.code2,t5.code2) as code2
      from table1 t1 
      join table2 t2 on t1.Individual_ID = t2.Individual_ID
      join table3 t3 on t1.Individual_ID = t3.Individual_ID
      join table4 t4 on t1.Individual_ID = t4.Individual_ID
      join table5 t5 on t1.Individual_ID = t5.Individual_ID
    

    【讨论】:

    • 您需要在选择列表中限定 Individual_ID。
    • @barbaros 有没有办法用 5 个不同的表来做到这一点?完全相同的场景,我只是想把 5 张桌子放在一起
    • @BarbarosÖzhan 现在如果每个表的 individual_ids 都是唯一的,我该怎么办?相同的列名,但没有一个列表具有相同的 individual_id
    猜你喜欢
    • 2021-03-20
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    相关资源
    最近更新 更多