仅列出不包含名称的样本

时间:2019-04-08 16:10:56

标签: sql sql-server

我正在尝试查询样本,以便仅在名称不包含“ CP”的情况下才显示结果。因此,如果名称为“ CP”,则不显示该样本的行,但是,如果名称为“ Dirt”或“ Dust”,则不显示该样本号的行。 / p>

这是我的尝试:

select distinct SampNum
from results
where (SampName = 'Dirt' or SampName = 'Dust')
  and SampName not in ('CP')

原始数据:

SampNum | SampName
1         'Dirt'
1         'Dust'
1         'CP'
2         'Dirt'
2         'Dust'
3         'Dust'
4         'CP'

预期输出:

SampNum                     
2               
3       

3 个答案:

答案 0 :(得分:2)

试一下...

select distinct SampNum 
from results 
where (SampName = 'Dirt' or SampName = 'Dust') 
and SampNum not in (Select SampNum From results Where SampName in ('CP'))

答案 1 :(得分:2)

您可以在此处使用EXCEPT来返回带有污垢或灰尘的SampNum-那些也具有CP的除外:

select SampNum
from results
where (SampName = 'Dirt' or SampName = 'Dust')
EXCEPT
select SampNum
from results
where SampName = 'CP'

dbfiddle https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=0bd2b69767319581d91fd5c484de2583

create table results (SampNum int, SampName varchar(10));
insert into results values (1,'Dirt');
insert into results values (1,'Dust');
insert into results values (1,'CP');
insert into results values (2,'Dirt');
insert into results values (2,'Dust');
insert into results values (3,'Dust');
insert into results values (4,'CP');

select SampNum
from results
where (SampName = 'Dirt' or SampName = 'Dust')
EXCEPT
select SampNum
from results
where SampName = 'CP';

返回:

SampNum
      2
      3

答案 2 :(得分:1)

您可以进行聚合:

select SampNum
from results
group by SampNum
having sum(case when SampName in ('Dirt', 'Dust') then 1 else 0 end) > 0 and
       sum(case when SampName = 'CP' then 1 else 0 end) = 0;