代码之家  ›  专栏  ›  技术社区  ›  menteith

在子查询的返回值上使用大小写

  •  0
  • menteith  · 技术社区  · 5 年前

    我想写信 case 从内部查询获取其输入的子句。请让我更详细地描述一下。

    假设我有一张桌子:

    create table food
    (   fruit varchar2(50),
        chips varchar2(50)
    );
    

    有价值观

    INSERT INTO food
    (fruit, chips)
    VALUES ('Apple', 'Paprika');
    
    INSERT INTO food
    (fruit, chips)
    VALUES ('Orange', 'Salt');
    

    DB Fiddle

    我想写一个查询,它将显示:

    水果,薯条,如果水果是“苹果”,则为1,否则为0

    'Apple', 'Paprika', 1
    'Orange, 'Salt', 0
    

    我不想为此使用联接。 它必须是子查询

    select f.fruit,
    ((case (select ff.fruit from food ff)
    when ff.fruit = 'Apple' then 1 else 0 end ) as is_apple) from food f;
    

    但是,我得到了以下错误 ORA-00905: missing keyword

    1 回复  |  直到 5 年前
        1
  •  0
  •   Ponder Stibbons    5 年前

    如果 它必须是子查询 然后使用 dual

    select fruit, chips, 
          (select case food.fruit when 'Apple' then 1 else 0 end from dual) is_apple 
      from food;
    

    或从中选择 food 使用主键(如果表中包含主键),或 rowid

    select fruit, chips, 
          case (select fruit from food ff where ff.rowid = food.rowid) 
              when 'Apple' then 1 
              else 0 
          end is_apple 
      from food;
    

    demo

        2
  •  4
  •   Aleksej    5 年前

    您不需要为此执行子查询:

    select fruit, chips,
           case when fruit = 'Apple'
             then 1
             else 0
           end as is_apple
    from food
    

    select fruit, chips,
           (select case when f2.fruit = 'Apple'
                     then 1
                     else 0
                   end
            from food f2
            where f.rowid = f2.rowid
            )
    from food f