0
在Oracle中,如何查找必須具有Feature1並且至少具有Feature2或Feature3中的一個的Cars。示例表和預期結果應如下圖所示。由於基蘭在Oracle中如何在同一列上使用子條件進行搜索
在Oracle中,如何查找必須具有Feature1並且至少具有Feature2或Feature3中的一個的Cars。示例表和預期結果應如下圖所示。由於基蘭在Oracle中如何在同一列上使用子條件進行搜索
這應該工作:
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
我喜歡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
我喜歡這種方法,因爲同樣的想法可以用於處理許多不同的類似疑問的 - 和條件,或條件的不同亞羣和不同的計數。
你有沒有試過任何SQL? – Randy