簡體   English   中英

在一列上選擇符合“僅/與”條件的記錄

[英]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);

參見帶有演示的SQL Fiddle

或者,您可以在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);

參見帶有演示的SQL Fiddle

這應該做

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM