需要没有交叉连接的完全外部连接

Need Full Outer Join without having Cross Join

需要连接两个 table 并且它们之间没有交叉连接。

加入条件需要在Tabl.month = Tab2.month

输入

 Table1          Table2
 Month ID        Month ID
 1     a         1     a
 1     b         1     b
 1     c         2     g
 2     d         3     i
 2     e         3     j
 3     f         3     k

输出:

Month_Tab1  ID_Tab1   Month_Tab2   ID_Tab2
1           a         1            a
1           b         1            b
1           c         Null         Null
2           d         2            g
2           e         Null         Null
3           f         3            i
Null        Null      3            j
Null        Null      3            k

上面的 o/p 是必需的,没有交叉连接,已经尝试了完全外部连接,但是由于两个表中的 ID 重复,所以发生了交叉连接。 Left/Right 加入也不适用,因为 table 中的任何一个可能有更大的 ID 集。

你想要一个 full join,但用 row_number() 来识别匹配项:

select t1.month month_tab1, t1.id id_tab1, t2.month month_tab2, t2.id id_tab2
from (
    select t.*, row_number() over(partition by month order by id) rn from table1 t
) t1 
full join (
    select t.*, row_number() over(partition by month order by id) rn from table2 t) t2       
on t2.month = t1.month and t2.rn = t1.rn

您可以使用完全外部联接:

select
  a.month,
  a.id,
  b.month,
  b.id
from (
  select month, id,
    row_number() over(partition by month order by id) as n
  from table1
) a
full outer join (
  select month, id,
    row_number() over(partition by month order by id) as n
  from table2
) b on b.month = a.month and b.n = a.n
order by coalesce(a.month, b.month), coalesce(a.n, b.n)