简体   繁体   English

WHERE子句SQL中的多个子条件

[英]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'. 我有一个表的以下示例,我希望从中获取Year为'2016'和'2017'的所有行,但要从Year'2017'中排除CustID'AB17'和'AB18'。 In total I should get 12 rows. 我总共应该得到12行。 See this fiddle 看到这个小提琴

Example: 例:

SQL: 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'. 年份为“ 2016”和“ 2017”,但要从“ 2017”中排除CustID“ AB17”和“ AB18”。

is: 是:

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

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

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