2

我创建了这个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

对于知识,我还能怎么做?

我从:

SELECT cola , s.f FROM #tbl1 cross apply(select colb as f from #tbl2) s

但是右边的部分有问题。

4

2 回答 2

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查询的最有效计划。

于 2012-10-25T12:30:29.580 回答
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
于 2012-10-25T12:37:25.923 回答