【问题标题】:Oracle select column as Sub query with case statementOracle 选择列作为带有 case 语句的子查询
【发布时间】:2017-08-02 06:37:54
【问题描述】:

我需要从返回 Flag 的 select 语句中的子查询中选择 Column NewFlag。什么时候 子查询与主查询具有匹配条件,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

【问题讨论】:

    标签: oracle oracle11g


    【解决方案1】:

    您实际上并不需要子选择。下面的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 中的保留字,您可能不应该将其用作表名。

    【讨论】:

    • 谢谢@Thomas Tschernich
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-05
      • 2013-03-25
      • 2013-07-26
      相关资源
      最近更新 更多