2

我有一个表,想要外连接另一个表,使用 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 )
4

2 回答 2

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
于 2009-03-18T13:32:52.763 回答
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
于 2009-04-10T12:19:56.657 回答