简体   繁体   English

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

[英]Using multiple conditions in where clause of SQL Server

I have a table called finalres in my database which has list of statuses and accounts.我的数据库中有一个名为finalres的表,其中包含状态和帐户列表。

I want to pull the accounts where the status should not be in:我想提取状态不应该在的帐户:

(xxx, ina, nfc)

Also I want to pull the accounts where the status in RWD but only when account# is null.我还想提取RWD中状态的帐户,但仅当帐户#为空时。 I wrote the below query but it only giving result for either one condition.我写了下面的查询,但它只给出任一条件的结果。 please help me.请帮我。

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

You can check this query at link below:您可以在下面的链接中查看此查询:

http://sqlfiddle.com/#!18/11b3d/2 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

You have your list of statuses (xxx, ina, nfc) that you do not want records with.您有不想记录的状态列表(xxx、ina、nfc)。 In addition, you only want records with a status of RWD when the account# is null, which means you need to add that status to you list of statuses that you do not want.此外,当 account# 为空时,您只需要状态为 RWD 的记录,这意味着您需要将该状态添加到您不想要的状态列表中。 That give you a query like this:这会给你一个这样的查询:

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

The problem is the status not in ('xxx','ina','nfc') allows the result to include any status ='rwd', even if the account# is not null.问题是status not in ('xxx','ina','nfc')允许结果包含任何status ='rwd',即使account#不为空。 This makes the (status='rwd' and account# is null) redundant.这使得(status='rwd' and account# is null)变得多余。 You will need to include the 'rwd' in the status not in query.您需要在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')

Try this,尝试这个,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM