合并基于 2 列的数据

merging data based on 2 columns

我有 2 个 table 格式如下。

Table 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

Table 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

我想创建一个输出 table,如下所示,它结合了两个 table 的 ID 和月份,同时从 2 个 table 中选择各自的度量值。

输出table:

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 查询吗?谢谢。

您需要一个基于 idmonthfull outer join:

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