将具有相同列但值不同的2个数据集组合

时间:2019-02-13 17:51:44

标签: sql join union

我有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列表和相同Column标头的多个表放在一起,但是与ID关联的列中的数据在我尝试的每个表中都不同聚在一起

3 个答案:

答案 0 :(得分:0)

您可以使用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;

答案 1 :(得分:0)

我认为您想要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;

答案 2 :(得分:0)

一种选择是使用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