使用IN的条件WHERE子句

时间:2018-03-22 16:16:55

标签: sql sql-server where-clause

我有一个SQL查询,我应该有类似

的东西
IMPORT LAYOUT "\\mypath\FY12P12" to FY12P12_Table

但这在IF和TransactionId上给我一个错误。

然后我试了

select  * from transactionDetails
WHERE OrderID in (400376, 400379)
AND
    IF TransactionDate <> ProcessingDate
        TransactionId in (2,3,9,14,15)
    ELSE
        TransactionId in (2,3,9)

但是这给了我两个&lt;&gt;的相同结果。和=条件 有人能告诉我我做错了吗?

由于

4 个答案:

答案 0 :(得分:1)

这两个人都不可能返回同样的东西。 <>=是互斥的。我怀疑你的测试或理解有问题。好吧,如果其中一个日期为null,那么它们都将返回false。他们不可能都回归真实。

(
    (TransactionDate <> ProcessingDate AND TransactionId in (2, 3, 9, 14, 15))
    OR
    (TransactionDate =  ProcessingDate AND TransactionId in (2, 3, 9))
)

我会在这里坚持并断言

where TransactionDate <> ProcessingDate 
  and TransactionDate =  ProcessingDate 

每次都会返回零行

答案 1 :(得分:0)

只需更好地组织括号,如数学句子

select  * from transactionDetails
WHERE OrderID in (400376, 400379)
AND`enter code here`
(
    (TransactionDate <> ProcessingDate AND TransactionId in (2,3,9,14,15))
    OR
  (TransactionDate = ProcessingDate AND TransactionId in (2,3,9))
)

答案 2 :(得分:0)

除上述答案外,您可能还想尝试使用UNION ALL代替OR并检查哪一个更快:

SELECT  * FROM transactionDetails
WHERE OrderID in (400376, 400379)
AND TransactionDate <> ProcessingDate 
AND TransactionId in (2,3,9,14,15)
UNION ALL
SELECT  * FROM transactionDetails
WHERE OrderID in (400376, 400379)
AND TransactionDate <> ProcessingDate 
AND TransactionDate = ProcessingDate 
AND TransactionId in (2,3,9)

答案 3 :(得分:0)

作为替代解决方案,您可以使用此功能。

select  * from transactionDetails
WHERE 
    OrderID in (400376, 400379)
    AND ( TransactionId in (2,3,9)
            OR ( TransactionDate <> ProcessingDate AND TransactionId IN (14,15) ) )