![](/img/trans.png)
[英]Selecting a column2 if column1 is not matching the required criteria
[英]Selecting records matching ONLY/AND criteria on one column
我希望能夠選擇只有亞洲人和白人的人。 例如,在下面的表格中,我唯一要檢索其記錄的人是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);
或者,您可以在hading子句中使用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'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.