2
votes

I need to join data from two different tables as shown below. Is that possible with only one sql query? If the "key" and "name" are on both tables, then it those are identical. "Status" is always "-" on table1 and "T" on table2. Also "name" and "comp" are match on both tables (example: Name3-C and Name4-B).
I have tried to do with "union" and "join" but no solution yet!

table1

t1.name     t1.time   t1.comp   t1.key   t1.status
name1        1          B         106        -
name2        2          B         -          -
name3        1          C         102        -
name4        3          B         103        -
name7        1          C         104        -

table2

t2.name     t2.time   t2.comp   t2.key    t2.status
name5        6          B         100        T
name6        5          B         -          T
name3        7          C         102        T
name4        9          B         103        T

RESULT should be...

name      time1    time2   t.comp   t.key   t.status
name1        1       -       B       106       -  
name2        2       -       B        -        -
name3        1       7       C       102       T
name4        3       9       B       103       T
name5        -       6       C       100       T
name6        -       5       B        -        T
name7        1       -       C       104       -


Thanks in advance!

3
Why would name5 6 B 100 be output as name5 - 6 C 100? Is that a typo? - Paul Williams

3 Answers

4
votes

If I understand correctly, you want a full outer join:

select coalesce(t1.name, t2.name) as name,
       t1.time as time1, t2.time as time2,
       coalesce(t1.comp, t2.comp) as comp,
       coalesce(t1.key, t2.key) as key,
       t2.status
from table1 t1 full outer join
     table2 t2
     on t1.key = t2.key and t1.name = t2.name;
0
votes
Select * from table1
union all 
Select * from table2

assuming the schemas of the tables are the same. If they aren't just add the fields from one table to another.

Select field1,field2,NULL,NULL from table1
union all 
Select NULL,NULL,field3,field4 from table2
0
votes
SELECT 
  T1.time AS Time1,
  T2.Time AS Time2,
  ISNULL(T1.COMP,T2.Comp) AS Comp,
  ISNULL(T1.Key,T2.Key)
FROM TABLE1 T1
FULL OUTER JOIN TABLE2 T2
ON T1.key = T2.key