2017-08-02 69 views
0

我需要從返回標記的select語句中的子查詢中選擇列NewFlag。當 子查詢與主要查詢具有匹配條件並且標誌具有結果'U'時,NewFlag 列應該是'/ U'else''。如果子查詢與主查詢不匹配,那麼NewFlag應該是'/ R'。Oracle選擇列作爲子查詢與case語句

Create table abc (ID int,SLSID int,FLag char) 

Create table master(ID int ,SLSID int) 

insert into abc values(1001,123,P) 
insert into abc values(1002,123,A) 
insert into abc values(1003,123,U) 
insert into abc values(1004,133,U) 

Insert into master (1001,123) 
Insert into master (1002,123) 
Insert into master (1003,123) 
Insert into master (1004,123) 

結果應該是

1003 123 '/U'  - since abc had matching entry in master and Flag is 'U' 
1001 123 ''   - since abc had matching entry in master but Flag is not 'U' 
1002 123 ''   - since abc had matching entry in master but Flag is not 'U' 
1004 133 '/R'  - no matching entry for abc in master 

回答

0

你並不真的需要一個子查詢中。以下OUTER JOIN會輸出你想要的結果。

select master.*, 
case 
    when abc.id is null then '/R' 
    when abc.flag = 'U' then '/U' 
    else null 
end flag 
from master 
left outer join abc on (master.id = abc.id and master.slsid = abc.slsid) 

注意MASTER是Oracle保留字,你可能不應該使用它作爲表名。

+0

謝謝@Thomas Tschernich –

0

相同的邏輯,托馬斯,但倒置加入到符合您想要的結果

select abc.id, abc.slsid, 
case 
    when master.id is null then '/R' 
    when abc.flag = 'U' then '/U' 
    else null 
end flag 
from abc 
left join master on (master.id = abc.id and master.slsid = abc.slsid);