查询,其中一个“和”条件并不总是适用

时间:2017-09-22 12:19:13

标签: sql sql-server

我基本上想在SQL查询中创建一个“if”函数。这是查询:

SELECT sum(amount), count(*) 
FROM Facilities 
    WHERE date = @Date 
    and system = 'LNI' 
    and entity is not NULL 
    and amount > 0
    and cust_cd != 'M' 
    and default_status = 'ACC' 
    and product_code NOT IN ('A', 'B', 'C')

    and expiration_date >= @Date

最后一个条件仅适用于此查询中捕获的某些行。

我想要存在的东西是这样的:

   and (product_code IN ('D', 'E')
      and expiration_date >= @Date )
 +
   and ( product_code IN ('F', 'G')
     and expiration_date = expiration_date)

我希望我正确地解释我的问题。有没有办法让“和”条件以其他因素为条件,或者我必须将它分成两个几乎相同的查询?

2 个答案:

答案 0 :(得分:2)

AND (
        (product_code IN ('D', 'E') AND expiration_date >= @Date)
     OR (product_code IN ('F', 'G') AND expiration_date = @Date)
     OR (product_code NOT IN ('D', 'E', 'F', 'G') OR product_code IS NULL) -- This line will make sure you get the rest. If all you want is the D/E and F/G conditions, remove this.
    )

这可能是最好的方法。当然,如果@Date可以为NULL,那么事情会变得更加繁琐。这种“全能”的查询非常困难。

答案 1 :(得分:0)

替代

AND ( CASE 
   WHEN product_code IN ('D', 'E') THEN expiration_date >= @Date 
   WHEN product_code IN ('F', 'G') THEN expiration_date = @Date
   ELSE TRUE 
END )

这避免了必须综合最终缺乏条件(@ HoneyBadger' s product_code NOT IN ('D', 'E', 'F', 'G') OR product_code IS NULL