SQL Server:连接所有左表并重复右键

时间:2016-04-28 13:15:18

标签: sql sql-server

我必须以下列方式加入表格:

表A:

1
2
3
4
5

表B:

A
B

结果表应为:

1 A
2 B
3 A
4 B
5 A

你有什么想法怎么做?

2 个答案:

答案 0 :(得分:1)

假设最坏的情况,表A中的列不是没有间隙的序列,并且表B中的行数事先不知道,您必须在两个表上应用ROW_NUMBER然后加入MODULO:

SELECT col1, col2
FROM
 (
   SELECT col1,
      ROW_NUMBER() OVER (ORDER BY col1) -1 AS rn
   FROM tableA
 ) AS A
JOIN 
 (
   SELECT col2,
      ROW_NUMBER() OVER (ORDER BY col2) -1 AS rn
   FROM tableB
 ) AS B
ON A.rn % (SELECT COUNT(*) FROM tableB) = B.rn

答案 1 :(得分:1)

也许是这样的:

select A.nr, case when (A.nr%2=0) then b2.chr else b3.chr end letter
from A, B b2, B b3
where b2.chr = 'A' and b3.chr = 'B'