gpt4 book ai didi

sql - 使用oracle在外连接中只获取一行

转载 作者:行者123 更新时间:2023-12-02 05:39:49 25 4
gpt4 key购买 nike

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

最佳答案

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

关于sql - 使用oracle在外连接中只获取一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/658259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com