Combine two tables in SQL Server 2008 R2 based on the third table

时间:2015-09-01 21:21:23

标签: sql sql-server sql-server-2008-r2

I need to combine two tables in SQL Server 2008 R2.

Tab1:

 id0, id1, id2, id3, value1
 100    38    89   91   23794
 120    29    60   11   98751

Tab2:

 id0, id1, id2, id3, value1
 100  78    96   30   9432

Tab3:

id1, id2, id3
 38    89   91
 78    96   30
 98    10   52
 29    60   11  

I need to combine tab1 and tab2 based on tab3. The id0 in tab2 is a subset of id0s in tab1.

The tab3 cover all combinations of id1, id2 and id3.

If the combination (id1, id2 id3) in tab3 is no available in tab1 or tab2, add it to tab4 and also assign 0 to value1.

If id0 in tab2 is not available in tab1, find all combinations of id1, id2, id3 with id0 and put them to tab4 and assign 0 to value1.

So, tab4 should be :

 id0, id1, id2, id3, value1
 100   38    89   91   23794
 100   78    96   30   9432
 100   98    10   52    0 
 100   29    60   11    0 
 120   29    60   11  98751
 120   98    10   52    0 
 120   78    96   30    0 
 120   38    89   91    0 

Any help would be appreciated.

2 个答案:

答案 0 :(得分:2)

You are just looking for left join:

select t3.*, coalesce(t1.value, t2.value, 0)
from table3 t3 left join
     table1 t1
     on t1.id1 = t3.id1 and t1.id2 = t3.id2 and t1.id3 = t3.id3 left join
     table1 t2
     on t2.id1 = t3.id1 and t2.id2 = t3.id2 and t2.id3 = t3.id3 ;

If combinations of ids can be duplicated in table1 or table2 or between them, then you might want an aggregation as well. But your question suggests this is not an issue.

EDIT:

The edited question looks a bit different, but I think you want:

select id0.id0, t3.id1, t3.id2, t3.id3,
       coalesce(t1.value, t2.value, 0)
from table3 t3 cross join
     (select id0 from table1 union select id0 from table2) id0 left join
     table1 t1
     on t1.id0 = id0.id0 and t1.id1 = t3.id1 and t1.id2 = t3.id2 and t1.id3 = t3.id3 left join
     table1 t2
     on t2.id0 = id0.id0 and t2.id1 = t3.id1 and t2.id2 = t3.id2 and t2.id3 = t3.id3 ;

This generates all the combinations using the cross join and then populates the value field from one of the tables.

答案 1 :(得分:0)

So LEFT JOIN both tables to Tab3, and add value1 from both:

SELECT t3.id1, t3.id2, t3.id3, IFNULL(t1.value1+t2.value1, 0) AS value1
FROM Tab3 t3 LEFT JOIN Tab1 t1
  ON t3.id1 == t1.id1 AND t3.id2 == t1.id2 AND t3.id3 == t1.id3 LEFT JOIN Tab2 t2
  ON t3.id1 == t2.id1 AND t3.id2 == t2.id2 AND t3.id3 == t2.id3