1

我希望能够选择只有亚洲人白人的人。例如,在我的下表中,我想为其检索记录的唯一人是 PersonId 1 和 2(期望的结果)。

桌子:

在此处输入图像描述

期望的结果:

在此处输入图像描述

4

3 回答 3

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

或者你可以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

于 2013-10-11T18:43:07.927 回答
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')
于 2013-10-11T18:35:01.730 回答
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'));
于 2013-10-11T18:43:53.840 回答