简体   繁体   中英

How to Filter multiple values for Where statement of SQL

Can any help on the below Query in the where statement in T-SQL?

I have ID & Product fields in table,in where condition need to exclude the ID not in('11','22','33') only when for Product='c'

Select ID,Product from Supplier
where 1=1 and Product in('A','B','C')

The statment should present

and ID not in('11','22','33')

Expecting when the Product='C', exclude the ID

You can try this

Select ID, Product from Supplier
where 1=1 and 
    ( Product in('A','B')
        OR ( Product = 'C' AND ID not in('11','22','33')) )

Use not exists

Select ID,Product from Supplier a
where 1=1 and Product in('A','B','C') and not exists 
(
  select 1 from supplier b where a.product=b.product and b.product='C' and
  b.ID in('11','22','33')
)

use not exists

 select * from table t1
 where not exists ( select 1 from table t2 where t1.Product=t2.Product
                              and t2.Product='C'
                              and ID in('11','22','33')
                  )
  and Product in('A','B','C')

It's Very simple

SELECT * FROM Supplier WHERE Product !='c' OR ( Id NOT IN(11,22,33) AND Product= 'c') 

Add your new condition.

SELECT * FROM Supplier WHERE (Product in ('a','b','c') and Product !='c' ) OR ( Id NOT IN(11,22,33) AND Product= 'c')

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