Oracle选择列作为带有case语句的Sub查询

时间:2017-08-02 06:37:54

标签: oracle oracle11g

我需要从select语句中的子查询中选择Column NewFlag,它返回Flag。什么时候 子查询与主查询具有匹配条件,Flag的结果为“U”,然后是NewFlag 列应该是'/ U'其他''。如果子查询与主查询不匹配,则NewFlag应为'/ R'。

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

2 个答案:

答案 0 :(得分: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中的保留字,您可能不应将其用作表名。

答案 1 :(得分:0)

与Thomas相同的逻辑,但使用倒置连接来匹配您想要的结果

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);