我有一个表,想要外连接另一个表,只使用Oracle 10g获取第二个表的第一行(nr最低的那个)。
编辑: nr在ID中是唯一的
Table x Table y
id id nr code
1 1 1 B
2 1 2 A
3 2 2 A
Expected result:
id nr code
1 1 B
2 2 A
3 NULL NULL
测试数据的示例(不对单行进行限制,但应允许更快的测试):
WITH
x AS( SELECT 1 id FROM dual UNION SELECT 2 FROM dual UNION SELECT 3 FROM dual ),
y AS( SELECT 1 id, 1 nr, 'B' code FROM dual
UNION SELECT 1, 2, 'A' FROM dual
UNION SELECT 2, 2, 'A' FROM dual
) -- end of test data
SELECT x.id, y.nr, y.code
FROM x
LEFT OUTER JOIN y ON ( y.id = x.id )
答案 0 :(得分:14)
WITH
x AS( SELECT 1 id FROM dual UNION SELECT 2 FROM dual UNION SELECT 3 FROM dual ),
y AS( SELECT 1 id, 1 nr, 'B' code FROM dual
UNION SELECT 1, 2, 'A' FROM dual
UNION SELECT 2, 2, 'A' FROM dual
) -- end of test data
SELECT *
FROM (
SELECT x.id, y.nr, y.code, ROW_NUMBER() OVER (PARTITION BY x.id ORDER BY y.nr) AS rn
FROM x
LEFT OUTER JOIN y
ON y.id = x.id
)
WHERE rn = 1
答案 1 :(得分:0)
WITH
x AS( SELECT 1 id FROM dual UNION SELECT 2 FROM dual UNION SELECT 3 FROM dual ),
y AS( SELECT 1 id, 1 nr, 'B' code FROM dual
UNION SELECT 1, 2, 'A' FROM dual
UNION SELECT 2, 2, 'A' FROM dual
) -- end of test data
SELECT x.id, y.nr, y.code
FROM x
LEFT OUTER JOIN y ON ( y.id = x.id )
WHERE rownum = 1 --Add this