从SQL中排除记录

时间:2017-02-11 06:48:15

标签: sql sql-server

我有一个查询

select * from tblSchool where schoolid=274988 and schooltype not in (2,5)

工作正常。

但我需要同时排除那些aType为'X'且asubtype为'Z'的记录。喜欢

select * from tblSchool where schoolid=274988 and schooltype not in (2,5)
EXCEPT
select * from tblSchool where aType='X' and asubtype = 'Z'

我能否做到这一点,除非,我的意思是在一个地方?

3 个答案:

答案 0 :(得分:2)

您可以将谓词添加到第一个选择中,如下所示:

select *
from tblSchool
where schoolid = 274988
    and schooltype not in (2, 5)
    and not (
        aType = 'X'
        and asubtype = 'Z'
        )

答案 1 :(得分:0)

您可以使用子查询,例如:

select * from tblSchool 
where schoolid=274988 
and schooltype not in (2,5)
and schoolid not in (select schoolid from tblSchool where aType='X' and asubtype = 'Z')

答案 2 :(得分:0)

只需使用NOT和大括号对2个排除标准进行分组:

SELECT *
FROM tblSchool
WHERE schoolid = 274988
AND schooltype NOT IN (2, 5)
AND NOT (aType = 'X' and asubtype = 'Z')