我有以下格式的2张桌子。
表1
ID Month Measure1 Measure2 Measure3
2 1 20 15 7
4 1 40 10 15
5 1 30 20 34
7 1 50 45 54
8 1 60 30 22
9 1 25 9 12
2 2 20 15 7
5 2 25 9 12
7 2 40 10 15
9 2 30 20 34
10 2 50 45 54
11 2 60 30 22
表2
ID Month Measure4 Measure5 Measure6
2 1 40 10 15
3 1 30 20 34
5 1 50 45 54
8 1 60 30 22
9 1 30 20 34
3 2 50 45 54
7 2 60 30 22
11 2 30 20 34
我想创建一个输出表,如下所示,该表将两个表的ID和月份组合在一起,同时从2个表中选择相应的度量值。
输出表:
ID Month Measure1 Measure2 Measure3 Measure4 Measure5 Measure6
2 1 20 15 7 40 10 15
3 1 30 20 34
4 1 40 10 15
5 1 30 20 34 50 45 54
7 1 50 45 54
8 1 60 30 22 60 30 22
9 1 25 9 12 30 20 34
2 2 20 15 7
3 2 50 45 54
5 2 25 9 12
7 2 40 10 15 60 30 22
9 2 30 20 34
10 2 50 45 54
11 2 60 30 22 30 20 34
您能通过SQL查询来帮助我吗?谢谢。
您需要基于full outer join
和id
的month
:
select
coalesce(t1.id, t2.id) id,
coalesce(t1.month, t2.month) month,
t1.measure1, t1.measure2, t1.measure3,
t2.measure4, t2.measure5, t2.measure6
from table1 t1 full outer join table2 t2
on t2.id = t1.id and t2.month = t1.month