我希望能够选择只有亚洲人和白人的人。例如,在我的下表中,我想为其检索记录的唯一人是 PersonId 1 和 2(期望的结果)。
桌子:
期望的结果:
有几种方法可以获得结果。
将 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);
或者你可以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);
这应该做
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')
非常幼稚,但应该工作。
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'));