简体   繁体   中英

multiple sub-conditions in WHERE clause SQL

I have the following example of a table from which I want all rows where Year is '2016' and '2017' but want to exclude CustID 'AB17' and 'AB18' from Year '2017'. In total I should get 12 rows. See this fiddle

Example:

SQL:

SELECT * FROM testing
WHERE Year In ('2016','2017') 
AND (CustID NOT In ('AB17','AB18') AND Year = '2017');

Table:

Year    CustID  Revenue
2016    AB12    10
2016    AB13    11
2016    AB14    12
2016    AB15    13
2016    AB16    14
2016    AB17    15
2016    AB18    16
2017    AB12    10
2017    AB13    11
2017    AB14    12
2017    AB15    13
2017    AB16    14
2017    AB17    15
2017    AB18    16
2018    AB12    17
2018    AB13    18
2018    AB14    19
2018    AB15    20
2018    AB16    21
2018    AB17    22
2018    AB18    23

Any suggestions?

This should work:

WHERE 
Year = '2016' 
OR (Year = '2017'  AND CustID NOT In ('AB17','AB18'))

A pretty direct translation of:

Year is '2016' and '2017' but want to exclude CustID 'AB17' and 'AB18' from Year '2017'.

is:

where year in (2016, 2017) and
      not (year = 2017 and custID in ('AB17', 'AB18'))

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