SQL Server:将具有不同列的两个表合并

时间:2018-10-18 15:34:43

标签: sql-server

我想合并两个具有不同列的表:

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

结果表将是

 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   

预先感谢

1 个答案:

答案 0 :(得分:1)

您需要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;