5

我正在尝试从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

但它返回0fortotalNULLfor purchase

4

2 回答 2

17

你的评论

我想使用案例陈述,你能澄清一下 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

于 2012-09-13T07:09:38.013 回答
4

我不认为 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'
 )
于 2012-09-13T06:30:04.433 回答