或者你可以使用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)
或max(letter)
,它具有相同的輸出,它給出了相同的輸出。重要的是你使用keep dense_rank
。另一個重要的事情是,訂單問題,我們使用order by src desc
來保持行時優先源表B。
而真正使其更短,使用keep dense_rank last
,並省略desc
訂單,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;
同樣,使用min
或max
上信不要緊,只要您保持dense_rank獲得優先級/首選行
字母 'B' 必須被排除,這裏是你的代碼的http://www.sqlfiddle。 com /#!4/0b796/13 –
好的一點 - 我誤以爲是rownum。更新了查詢以反映這一點。 –