Sophie Fu
Sophie Fu

Reputation: 43

SQL Server : Union two tables with different columns

I'd like to union two tables with different columns:

Table 1:                                 Table 2:

Name  Region  Price_2018 Cost_2018       Name Region Price_2017 Cost_2017
-----------------------------------      ---------------------------------
A     US      12         32              A    US     30         56
B     CH      20         15              D    JP     45         20
C     EU      30         16              B    CH     60         30

The result table will be

 Name  Region  Price_2018 Cost_2018 Price_2017 Cost_2017
 -------------------------------------------------------
 A     US      12         32        30         56
 B     CH      20         15        60         30
 C     EU      30         16        null       null
 D     JP      null       null      45         20   

Thanks in advance

Upvotes: 2

Views: 3023

Answers (1)

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

You need full outer join :

select coalesce(t1.name, t2.name), coalesce(t1.Region, t2.Region),
       t1.Price_2018, t1.Cost_2018, t2.Price_2017, t2.Cost_2017
from table1 t1 full outer join
     table2 t2
     on t2.name = t1.name;

Upvotes: 3

Related Questions