在Oracle中,如何找到必须具有Feature1并且至少具有Feature2或Feature3中的一个的Cars。样本表和预期结果应如下面的屏幕截图所示。谢谢Kiran
答案 0 :(得分:1)
这应该有效:
select t1.car, t1.feature
from yourtable t1
inner join
( -- inner select returns the cars with the Feature1 and Feature2 or Feature3
select car, feature
from yourtable
where feature = 'Feature1'
and exists (select car
from yourtable
where feature in ('Feature2', 'Feature3'))
) t2
on t1.car = t2.car
where t1.feature in ('Feature1', 'Feature2', 'Feature3') -- this excludes any other features
答案 1 :(得分:0)
我喜欢使用GROUP BY和HAVING:
select car
from t
group by car
having max(case when feature = 'Feature1' then 1 else 0 end) = 1 and
max(case when feature in ('Feature1', 'Feature2') then 1 else 0 end) = 1
此查询返回汽车。为了获得这些特色,你必须加入以下:
select t.*
from (select car
from t
group by car
having max(case when feature = 'Feature1' then 1 else 0 end) = 1 and
max(case when feature in ('Feature1', 'Feature2') then 1 else 0 end) = 1
) c join
t
on t.car = c.car
我喜欢这种方法,因为同样的想法可用于处理许多不同的类似查询 - AND条件,OR条件,不同的子组和不同的计数。