或者您可以使用特定于 Oracle 的技术来缩短代码:http ://www.sqlfiddle.com/#!4/0b796/11
with a as
(
select Num, 'A' as src, Letter
from tblA
union
select Num, 'B' as src, Letter
from tblB
)
select Num, min(Letter) keep(dense_rank first order by src desc) as Letter
from a
group by Num
order by Num;
输出:
| NUM | LETTER |
----------------
| 1 | A |
| 2 | C |
| 3 | D |
| 4 | E |
无论min(letter)
or max(letter)
,代码都可以工作,它具有相同的输出,它给出相同的输出。重要的是您使用keep dense_rank
. 另一个重要的事情是,顺序问题,我们order by src desc
在保持一行时会优先考虑源表B。
为了真正让它更短,使用keep dense_rank last
并省略desc
on order by,asc
无论如何都是默认的http://www.sqlfiddle.com/#!4/0b796/12
with a as
(
select Num, 'A' as src, Letter
from tblA
union
select Num, 'B' as src, Letter
from tblB
)
select Num, min(Letter) keep(dense_rank last order by src) as Letter
from a
group by Num
order by Num;
同样,在 Letter 上使用min
ormax
并不重要,只要您保持 dense_rank 获得优先/首选行