我有两个查询输出如下 -
A
乙
C
1
2
3
4
5
现在我期待加入这两个输出,它将返回以下输出 -
A | 1
B | 2
C | 3
NULL | 4
NULL | 5
注意:查询1和输出之间没有关系。 2
提前致谢,mkRabbani
答案 0 :(得分:2)
该关系基于表A和B中的值的顺序,因此我们LEFT JOIN
从A(包含数字)到有序索引上的B(包含字符)的结果的结果。
DECLARE @a TABLE (col int);
DECLARE @b TABLE (col char(1));
INSERT INTO @a VALUES (1);
INSERT INTO @a VALUES (2);
INSERT INTO @a VALUES (3);
INSERT INTO @a VALUES (4);
INSERT INTO @a VALUES (5);
INSERT INTO @b VALUES ('A');
INSERT INTO @b VALUES ('B');
INSERT INTO @b VALUES ('C');
SELECT B.col, A.col
FROM ( SELECT col, ROW_NUMBER() OVER(ORDER BY col) AS RowNum FROM @a ) AS A
LEFT JOIN ( SELECT col, ROW_NUMBER() OVER(ORDER BY col) AS RowNum FROM @b ) AS B ON A.RowNum = B.RowNum
答案 1 :(得分:1)
答案 2 :(得分:0)
Create Table T1 (col1 nVarchar(10))
Go
Create Table T2 (col1 nvarchar(10))
Go
Insert T1 (col1) Values ('A'), ('B'), ('C')
Insert T2 (col1) Values ('1'), ('2'), ('3'), ('4'), ('5')
Go
;With CTE1 As (
Select col1,
Row_Number() Over(Order By Col1) Rn
From T1
), CTE2 As (
Select col1,
Row_Number() Over(Order By Col1) Rn
From T2
)
Select CTE1.col1, CTE2.col1 From CTE1 Right Outer Join
CTE2 On CTE1.Rn = CTE2.Rn