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

gorkyyrv  于 2022-11-21  发布在  SQL Server
关注(0)|答案(4)|浏览(297)

我的数据库中有一个名为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')
vvppvyoh

vvppvyoh1#

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
rjee0c15

rjee0c152#

您有一个状态列表(xxx、ina、nfc),您不希望记录具有这些状态。此外,当帐号为空时,您只希望记录具有RWD状态,这意味着您需要将该状态添加到您不希望的状态列表中。这将为您提供如下查询:

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

bfrts1fy3#

问题是status not in ('xxx','ina','nfc')允许结果包含任何status ='rwd',即使account#不为空。这使得(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')
a11xaf1n

a11xaf1n4#

试试这个

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

相关问题