2013-10-11 46 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')); 
相关问题