2013-10-11 47 views

回答

4

有,你可以得到結果的幾種方法。

使用HAVING子句與聚合函數:

select personid, race 
from yourtable 
where personid in 
    (select personid 
    from yourtable 
    group by personid 
    having 
     sum(case when race = 'white' then 1 else 0 end) > 0 
     and sum(case when race = 'asian' then 1 else 0 end) > 0 
     and sum(case when race not in('asian', 'white') then 1 else 0 end) = 0); 

SQL Fiddle with Demo

或者您也可以在HAVING子句中使用count(distinct race)

;with cte as 
(
    select personid 
    from yourtable 
    where race in ('white', 'asian') 
    and personid not in (select personid 
         from yourtable 
         where race not in ('white', 'asian')) 
    group by personid 
    having count(distinct race) = 2 
) 
select personid, race 
from yourtable 
where personid in (select personid 
        from cte); 

SQL Fiddle with Demo

+0

謝謝!我喜歡第二種解決方案,因爲這看起來很容易通過一些輸入參數來插入比賽值和計數值。 – gooseman

2

這應該做

select * from table where personID in (
select personID from table 
group by personID having count(distinct race) = 2 and min(race) = 'Asian' 
and max(race) = 'White') 
+0

這個工程,但沒有使用最大和最小限制我只使用兩場比賽?如果我想做同樣的查詢但是參加3個或更多比賽怎麼辦? (這絕對是我的情況)。 – gooseman

+0

@ leo.t,在這種情況下,我會將您推薦給Bluefeet的解決方案 – iruvar

0

非常天真,但應該工作。

select * from yourtable t1 join yourtable t2 on t1.id = t2.id where ((t1.race = 'Asian' and t2.race = 'White') OR (t1.race = 'White' and t2.race = 'Asian')) and t1.id not in (select id from yourtable where race not in ('Asian','white')); 
相關問題