在SQL WHERE子句CASE语句(CASE Statement in SQL WHERE cla

2019-09-22 08:35发布

我想取其中我使用的是从表中的数据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

但它返回0totalNULLpurchase

Answer 1:

从您的评论 。

我想用Case语句,可以ü请澄清我有关情况statament 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 。 否则你不会得到想要的结果。 有关详细说明,请参见本SQLFiddle



Answer 2:

我不认为情况下,可以这样的。 你想要的是一个稍微复杂的表达式作为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'
 )


文章来源: CASE Statement in SQL WHERE clause
标签: mysql case