gige
gige

Reputation: 322

Join two tables in sql-server 2008

I have two tables:

Table A :

Id (int), TypeA (varchar(25))
  1        a
  2        Null
  3        b
  4        c
  5        d
  6        v

Table B :

Id (int), TypeB (varchar(25))
  2        A
  3        C
  4        null
  5        E
  7        S

The result should be:

Id (int), TypeA (varchar(25)), TypeB (varchar(25))
  1         a                   Null
  2         Null                A   
  3         b                   C
  4         c                   Null
  5         d                   E
  6         v                   Null
  7         Null                S

Any idea? Thanks

Upvotes: 1

Views: 68

Answers (2)

Chiragkumar Thakar
Chiragkumar Thakar

Reputation: 3726

You can try this, this is somewhat low quality answer but it will help you to resolve your issue for sure.

SELECT ID,TypeA, TypeB FROM (
    SELECT A.ID, A.TypeA, B.TypeB FROM TableA AS A LEFT JOIN TableB AS B ON A.ID = B.ID 
    UNION
    SELECT B.ID, A.TypeA, B.TypeB FROM TableA AS A RIGHT JOIN TableB AS B ON A.ID = B.ID
) AS TableTemp
GROUP BY ID,TypeA, TypeB

Upvotes: 1

Hell Boy
Hell Boy

Reputation: 981

Use this code:

CREATE TABLE #t1 (id INT, NAME VARCHAR(25))
CREATE TABLE #t2 (id INT, NAME VARCHAR(25))
insert into #t1 values(1,'a')
insert into #t1 values(2,NULL)
insert into #t1 values(3,'b')
insert into #t1 values(4,'c')
insert into #t1 values(5,'d')
insert into #t1 values(6,'v')

insert into #t2 values(2,'A')
insert into #t2 values(3,'C')
insert into #t2 values(4,NULL)
insert into #t2 values(5,'E')
insert into #t2 values(7,'S')


select * from #t1
select * from #t2


select a.name,b.name from #t1 a
FULL OUTER JOIN #t2 b
ON a.id=b.id

Results:

name    name
a      NULL
NULL    A
b       C
c      NULL
d       E
v      NULL
NULL    S

Upvotes: 0

Related Questions