合并 SQL 中的两列,无需键且列内无重复项

Combining two columns in SQL wwithout a key and no duplicate within columns

无论如何我们可以独立组合两列(匹配“索引”)并在没有匹配的地方有 NULLS 。让我们看下面的例子

col1
-----
A
B
C
D

Col2
----
1
2

期望的输出

 Col1    Col2
 ------------
 A       1
 B       2
 C       
 D       

我尝试了 left joininner joinouter joincross join

的不同变体

您可以使用 row_number() 执行此操作。一种方法:

select t1.col1, t2.col2
from (select t1.*, row_number() over (order by col1) as seqnum
      from table1 t1
     ) t1 full join
     (select t2.*, row_number() over (order by col2) as seqnum
      from table1 t2
     ) t2
     on t2.seqnum = t1.seqnum;

注意:无论哪个 table 有更多行,这都有效。