我有一个带有字段代码的表a和带有字段代码的表b 我需要
a.code b.code
------ ------
1 4
2 5
6 8
表a
code
----
1
2
6
表b
code
----
4
5
8
如何使用单个查询执行此操作?
答案 0 :(得分:2)
使用Row_number
加CTE
。试试这个。
;WITH cte1
AS (SELECT Row_number()OVER(ORDER BY Code) rn,
Code
FROM table1),
cte2
AS (SELECT Row_number()OVER(ORDER BY Code) rn,
Code
FROM table2)
SELECT a.Code,
b.Code
FROM cte1 a
JOIN cte2 b
ON a.rn = b.rn
或
SELECT a.code,
b.code
FROM (SELECT Row_number()OVER(ORDER BY code) rn,
code
FROM table1) a
INNER JOIN (SELECT Row_number()OVER(ORDER BY code) rn,
code
FROM table2) b
ON a.rn = b.rn
更新:对于Ms-Access,请使用correlated subquery
执行此操作
SELECT a.code,
b.code
FROM (SELECT code,
(SELECT Count(1)
FROM tablea s
WHERE s.code >= f.code) rn
FROM tablea f) a
INNER JOIN (SELECT (SELECT Count(1)
FROM tableb s
WHERE s.code >= f.code) rn,
code
FROM tableb f) b
ON a.rn = b.rn