我有2张桌子
Table1
Year,Month, data
2017,1,2
2018,2,10
Table2
Year,Month,data2
2017,1,5
2019,2,2
我正在尝试将表合并为1个表,其中我们从这两个表中获取所有行,如下所示。
Year,Month,data,data2
2017 ,1,2,5
2018,2,10,NULL
2019,2,NULL,2
似乎标准外部联接在这里不起作用,我也不能使用Union ALL 是否有某种外部联接查询可以完成此任务?
答案 0 :(得分:2)
您应该使用UNION从两个表中获取年份和月份,并使用左连接将其与table1和table2相关联
select a.Year , a.Month, b.data, c.data2
from (
select Year,Month
from Table1
union
select Year,Month
from Table2
) a
left join table1 b on a.Year = b.Year and a.month = b. month
left join table2 c on a.Year = c.Year and a.month = c. month
答案 1 :(得分:1)
您真正想要的是full join
。一种常用的方法是union all
和group by
:
select year, month, max(data) as data, max(data2) as data2
from ((select year, month, data, null as data2
from table1
) union all
(select year, month, null, data2
from table2
)
) t
group by year, month;