选择在一列上匹配ONLY / AND条件的记录

时间:2013-10-11 18:30:04

标签: sql sql-server

我希望能够选择亚洲人白人。例如,在我的下表中,我唯一想要检索记录的人是PersonId 1和2(Desired Result)。

表:

enter image description here

期望的结果:

enter image description here

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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')

答案 2 :(得分: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'));