我创建了这个sql DEMO:
我有#tbl1:
___cola__
1
2
3
4
和#tbl2:
_colb_
a
b
c
d
我想要这个:
_colb____|__cola____
a 1
b 2
c 3
d 4
我找到了一个解决方案(糟糕的恕我直言)
SELECT table1.cola, table2.colb FROM
(SELECT cola, ROW_NUMBER() OVER (ORDER BY cola) AS rn1 FROM #tbl1) table1,
(SELECT colb, ROW_NUMBER() OVER (ORDER BY colb) AS rn2 FROM #tbl2) table2
WHERE table1.rn1 = table2.rn2
知识, 我怎么能 ELSE 呢?
我开始时:
SELECT cola , s.f FROM #tbl1 cross apply(select colb as f from #tbl2) s
但正确的部分存在问题。
答案 0 :(得分:6)
这是另一种选择:
SELECT cola, colb
FROM (
SELECT a.cola, b.colb,
rna=row_number() over (partition by colb
order by cola),
rnb=row_number() over (partition by cola
order by colb)
FROM #tbl1 a
CROSS JOIN #tbl2 b
) X
WHERE rna=rnb;
另一个:
;WITH
a1 AS (SELECT cola, ROW_NUMBER() OVER (ORDER BY cola) AS rn1 FROM #tbl1),
a2 AS (SELECT colb, ROW_NUMBER() OVER (ORDER BY colb) AS rn2 FROM #tbl2)
SELECT a1.cola, a2.colb
FROM a1
JOIN a2 on a1.rn1=a2.rn2;
但说实话,第二个是重新排列查询的部分 - 执行计划与您拥有的完全相同。它有效,并且是这种zip-up
查询的最有效计划。
答案 1 :(得分:0)
;with CTE1 as (select col1,row_number() over (order by (select 0)) as rn from #tbl1)
,with CTE2 as (select col1,row_number() over (order by (select 0)) as rn from #tbl2)
select c1.col1,c2.col1 from CTE1 c1 inner join CTE2 c2
on c1.rn=c2.rn