2012-09-07 51 views

回答

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

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 

該查詢返回的汽車。爲了得到featuers還有,你必須加入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 

我喜歡這種方法,因爲同樣的想法可以用於處理許多不同的類似疑問的 - 和條件,或條件的不同亞羣和不同的計數。

相關問題