简体   繁体   中英

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.

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. 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

 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. 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. 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. This makes the (status='rwd' and account# is null) redundant. You will need to include the 'rwd' in the status not in query.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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