根据列过滤掉行中的重复项

时间:2016-10-05 12:46:34

标签: sql oracle plsql

说我有两列:

Fruit Condition
apple   unripe
banana  ripe
apple   ripe
banana  moldy
peach   moldy
peach   ripe
apple   ripe
pineapple soldout

我只想知道哪种水果成熟或未熟,不发霉或售罄(只有苹果)

Select fruit
from example
where (condition <> 'moldy' or condition <> 'soldout')
and (condition = 'ripe' or condition = 'unripe')
group by fruit

无效

4 个答案:

答案 0 :(得分:3)

您可以将HAVING子句与CASE EXPRESSION用于此目的:

SELECT t.fruit FROM YourTable t
GROUP BY t.fruit
HAVING COUNT(CASE WHEN t.condition in ('ripe','unripe') THEN 1 END) > 0
        -- makes sure at least 1 attribute of ripe/unripe exists
   AND COUNT(CASE WHEN t.condition in ('soldout','moldy') THEN 1 END) = 0
        -- makes sure no attribute of soldout/moldy exists

答案 1 :(得分:2)

您正在使用or。这是错误的做法。

使用:

where not (condition = 'moldy' or condition = 'soldout')

或使用

where (condition <> 'moldy' and condition <> 'soldout')

然后,我假设你想要的水果只是成熟或未成熟。

select distinct Fruit
from Example E1
where Condition in ('ripe','unripe')
and not exists 
    (
    select E2.Fruit 
    from Example E2 
    where E1.Fruit = E2.Fruit
    and E2.Condition in ('moldy','soldout')
    )

答案 2 :(得分:2)

试试这个:

select distinct fruit from example where fruit not in
(
select fruit from example 
where condition in ('soldout', 'moldy')
);

答案 3 :(得分:2)

这个怎么样:

with example as
    ( select 'apple' as fruit, 'unripe' as condition from dual union all
      select 'banana',    'ripe' from dual union all
      select 'apple',     'ripe' from dual union all
      select 'banana',    'moldy' from dual union all
      select 'peach',     'moldy' from dual union all
      select 'peach',     'ripe' from dual union all
      select 'apple',     'ripe' from dual union all
      select 'pineapple', 'soldout' from dual )
select fruit from example
where  condition in ('ripe','unripe')
minus
select fruit from example
where  condition in ('moldy','soldout');
相关问题