首页 > 解决方案 > 转移到 Oracle 中正确位置的数据

问题描述

我有一张如下表。我的目标是计算水果下的苹果和芒果。

我想使用 case when 语句来做到这一点。我运行了这个查询,但它没有用。

这有效:

CASE 
    WHEN Food_type = 'vegetables' 
         AND Names IN ('apple', 'mango') 
       THEN 1 
       ELSE 0 
END IN (0)


CASE 
    WHEN Names IN ('apple', 'orange', 'mango') 
       THEN 'fruit' 
END Food_type2

输出:

名称 食物类型
苹果 蔬菜
茄子 蔬菜
萝卜 蔬菜
水果
洋葱 蔬菜
菠菜 蔬菜
芒果 蔬菜

我怎样才能做到这一点 ?谢谢你。

标签: sqloracle

解决方案


这个?采样数据直到第 9 行;查询从第 10 行开始。

SQL> with test (names, food_type) as
  2    (select 'apple'   , 'vegetables' from dual union all
  3     select 'eggplant', 'vegetables' from dual union all
  4     select 'carrot'  , 'vegetables' from dual union all
  5     select 'orange'  , 'fruit'      from dual union all
  6     select 'onion'   , 'vegetables' from dual union all
  7     select 'spinach' , 'vegetables' from dual union all
  8     select 'mango'   , 'vegetables' from dual
  9    )
 10  select case when names in ('apple', 'mango') or food_type = 'fruit' then 'fruit'
 11              else 'vegetables'
 12         end food_type,
 13         count(*)
 14  from test
 15  group by
 16         case when names in ('apple', 'mango') or food_type = 'fruit' then 'fruit'
 17              else 'vegetables'
 18         end;

FOOD_TYPE    COUNT(*)
---------- ----------
vegetables          4
fruit               3

SQL>

推荐阅读