SQL WHERE子句中的CASE语句

时间:2012-09-13 06:26:44

标签: mysql case

我正在尝试从CASE子句中使用WHERE条件的表中获取数据,目前我正在使用以下查询: -

SELECT count(enq_id) AS total, sum(purchase_amount) AS purchase
FROM temp_stock
WHERE purchase_date <> '0000-00-00'
AND purchase_date < '2012-08-01'
AND (

STATUS = 'Sold'
OR STATUS = 'In Stock'
OR STATUS = 'Ref'
)
AND CASE WHEN (

STATUS = 'Sold'
)
THEN delivery_date >= '2012-08-01'
END

但它会为0返回total,为NULL返回purchase

2 个答案:

答案 0 :(得分:17)

来自your comment

  

我想使用案例陈述,请你澄清一下where子句

中的案例陈述

您可以在CASE中使用WHERE语句,如下所示:

SELECT count(enq_id) AS total, sum(purchase_amount) AS purchase
FROM temp_stock
WHERE purchase_date <> '0000-00-00'
AND purchase_date < '2012-08-01'
AND (    STATUS = 'Sold'
      OR STATUS = 'In Stock'
      OR STATUS = 'Ref')
AND CASE STATUS 
         WHEN 'Sold' 
         THEN delivery_date >= '2012-08-01'
         ELSE 1=1
    END

您需要使用ELSE 1=1。否则你不会得到理想的结果。有关详细说明,请参阅this SQLFiddle

答案 1 :(得分:3)

我不认为CASE可以这样工作。你想要的是一个稍微复杂的表达式作为你的WHERE子句。可能是这样的:

SELECT count(enq_id) AS total, sum(purchase_amount) AS purchase
FROM temp_stock
WHERE purchase_date <> '0000-00-00'
  AND purchase_date < '2012-08-01'
  AND (
     (STATUS = 'Sold' AND delivery_date >= '2012-08-01')
   OR STATUS = 'In Stock'
   OR STATUS = 'Ref'
 )