在 Oracle 中,我如何找到必须具有 Feature1 并且至少具有 Feature2 或 Feature3 之一的汽车。示例表和预期结果应如下图所示。谢谢基兰
问问题
435 次
2 回答
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
见SQL Fiddle with Demo
于 2012-09-07T14:34:26.620 回答
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
此查询返回汽车。要获得这些功能,您必须重新加入 tis:
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 条件、不同的子组和不同的计数。
于 2012-09-07T14:56:46.503 回答