我正在尝试从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
。
答案 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'
)