SQL - 包含多个AND和NOT IN的WHERE子句

时间:2015-08-14 10:29:24

标签: sql-server tsql

我想返回不在FocusRegion Canada中的值,但我仍然希望看到来自其他FocusRegion的所有值。 (但如果你在澳大利亚,那么你需要有一个FirstPurchaseDate< = 2001-11-19 21:39:12.000)

这是我的代码,无法让它工作。

SELECT FocusRegion, FirstPurchasedDate 
FROM TabelName
WHERE FocusRegion NOT IN ('Canada') 
AND (FocusRegion NOT IN ('Australia') AND FirstPurchasedDate <= '2001-11-19 21:39:12.000')

4 个答案:

答案 0 :(得分:1)

您似乎需要使用OR代替AND,因为当您使用AND时,您说它应该不是来自澳大利亚并且日期&lt; = 2001- 11-19 ,对你有什么不对,你应该在下面使用它:

SELECT FocusRegion, FirstPurchasedDate 
FROM TabelName
WHERE FocusRegion NOT IN ('Canada') 
AND (FocusRegion NOT IN ('Australia') OR FirstPurchasedDate <= '2001-11-19 21:39:12.000')

答案 1 :(得分:1)

您为什么使用X IN (Y)?只需使用X != Y即可。这是您的疑问:

SELECT FocusRegion, FirstPurchasedDate 
FROM TabelName
WHERE FocusRegion != 'Canada'
AND (FocusRegion != 'Australia' 
  OR FirstPurchasedDate <= '2001-11-19 21:39:12.000')

答案 2 :(得分:0)

绝对值得使用NOT运算符。

你不想要任何在澳大利亚和> '2001-11-19 21:39:12.000'

的地方
SELECT FocusRegion, FirstPurchasedDate 
FROM TableName
WHERE FocusRegion <> 'Canada'
  AND NOT (FocusRegion = 'Australia' AND FirstPurchasedDate > '2001-11-19 21:39:12.000');

答案 3 :(得分:0)

我认为这更易于阅读 - 并且更贴切地反映了您在问题描述中详述的逻辑:

SELECT FocusRegion, FirstPurchasedDate 
FROM   TabelName
WHERE 
       FocusRegion <> 'Canada' 
       OR 
          (
            FocusRegion = 'Australia' AND 
            FirstPurchasedDate <= '2001-11-19 21:39:12.000'
          );