表的并列

时间:2019-03-19 10:06:11

标签: sql sql-server

我有表A:

Id
________
-1
-2
-3

我有表B:

Id
_________
110
111
112

如何从表A和表B中获取包含列的结果表的最佳实践:

IdA | IdB
__________
-1  | 110
-2  | 111
-3  | 112

3 个答案:

答案 0 :(得分:3)

一种方法是使用几个CTE和ROW_NUMBER。我假定,值应分别以降序和升序连接。这意味着,如果要分别添加值-4109,则-1109将被联接,而不是-1110 (以及-4112)。

WITH A AS(
    SELECT Id,
           ROW_NUMBER() OVER (ORDER BY Id DESC) AS I
    FROM TableA),
B AS(
    SELECT ID
           ROW_NUMBER() OVER (ORDER BY ID ASC) AS I
    FROM TableB)
SELECT A.ID AS IdA,
       B.ID AS IdB
FROM A
     JOIN B ON A.I = B.I;

答案 1 :(得分:2)

这是一个很好的解决方案。

SELECT AA.Id AS IdA ,BB.Id As IdB  FROM 
 (SELECT Id, ROW_NUMBER() OVER(ORDER BY (SELECT 100)) As row_num FROM A ) AS AA
 INNER JOIN 
 (SELECT Id, ROW_NUMBER() OVER(ORDER BY (SELECT 100)) AS row_num  FROM B)  AS BB
 ON AA.row_num = BB.row_num 

答案 2 :(得分:1)

使用数据集中的row_number()(我假设两个表列的项目数均相同)

with cte as
(select id,row_number()over(order by (select null)) rn
 from tableA
),cte1 as
( 
select id,row_number()over(order by (select null)) rn from tableB
) select cte.id,cte1.id cte join ct1 on ct1.rn=cte.rn