在SQL Server的where子句中使用多个条件

时间:2018-09-25 13:26:32

标签: sql sql-server operators where-clause

我的数据库中有一个名为finalres的表,其中包含状态和帐户列表。

我想提取状态不应该存在的帐户:

(xxx, ina, nfc)

我也想拉RWD中状态为“ {”的帐户,但仅当帐户号为空时才可以。我写了下面的查询,但它只给出任一条件的结果。请帮助我。

select *
from finalres
where 1 = 0
   or (status = 'rwd' and account# is null)
   or status not in ('xxx', 'ina', 'nfc')

4 个答案:

答案 0 :(得分:0)

select * from finalres where 
(status='rwd' and account# is null) 
 or  status not in ('xxx','ina','nfc')

您可以在下面的链接中检查此查询:

http://sqlfiddle.com/#!18/11b3d/2

 CREATE TABLE finalres
(
  [account] int,
  [ItemNo] varchar(32),
  status varchar(100)

) 

INSERT INTO finalres (account, ItemNo, status) VALUES
  ('1', '453', 'xxx'),
  ('2', '657', '34'),
  (null, '657', 'rwd')
  ;


account     ItemNo  status
2            657     34
(null)       657     rwd

答案 1 :(得分:0)

您有不想记录的状态列表(xxx,ina,nfc)。此外,当帐户号为null时,您只希望记录状态为RWD的记录,这意味着您需要将该状态添加到不需要的状态列表中。这样会给您这样的查询:

select
    *
from
    finalres
where
     status not in ('rwd','xxx','ina','nfc')
  or (status='rwd' and account is null)

答案 2 :(得分:0)

问题是status not in ('xxx','ina','nfc')允许结果包含任何status ='rwd',即使account#不为null。这使得(status='rwd' and account# is null)成为多余的。您需要在status not in查询中包含“ rwd”。

select 
*
from finalres
where 1 = 0
or (status='rwd' and account# is null)
or status not in ('rwd','xxx','ina','nfc')

答案 3 :(得分:-1)

尝试一下

    select * 
      from finalres 
     where (status='rwd' and account# is null) 
        or status not in ('xxx','ina','nfc')