2016-10-05 130 views
3

行重复说我有2列:筛选出基于列

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 

不工作

回答

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') 
    ) 
+0

这是事实,但它仍然不能解决我的情况。 –

+0

@JacobAlley查看更新 – JohnHC

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 
+0

谢谢,我会认为这会工作,但它说我错过了一个关键词的“>”符号 –

+0

你已经把你的'HAVING'操作符放入你的'CASE'中错误 – JohnHC

+0

@ JacobAlley现在可以工作了。 – sagi

2

试试这个:

select distinct fruit from example where fruit not in 
(
select fruit from example 
where condition in ('soldout', 'moldy') 
); 
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');