在mysql的情况下使用Where子句

时间:2016-10-04 14:16:58

标签: mysql switch-statement case where between

以下是我的查询,我正确获取相关状态值的总数。但我需要在特定时间范围内的那些值。获取以下总值是我的查询。

SELECT 
SUM(CASE 
     WHEN `status` = 'saved_for_review' THEN 1
     ELSE 0
   END) AS SavedCases,
SUM(CASE 
     WHEN STATUS = 'send_to_warehouse' THEN 1
     ELSE 0
   END) AS SendtoWareshouse,
SUM(CASE 
     WHEN STATUS = 'send_to_cep' THEN 1
     ELSE 0
   END) AS SendtoCEP,
   SUM(CASE 
     WHEN STATUS = 'Successful' THEN 1
     ELSE 0
   END) AS Closed 
FROM table_details

但我需要特定时间范围内的值,如

where date(created_on) between '20160701' and '20160901'

如何将此where子句添加到上述查询中。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

首先,只需编写SUM(status='saved_for_review') SavedCases就可以了,而且更简单,更快捷。至于WHERE子句,只需在FROM子句之后添加它。

SELECT 
    SUM(status = 'saved_for_review') SavedCases,
    SUM(status = 'send_to_warehouse') SendtoWarehouse,
    SUM(status = 'send_to_cep') SendtoCEP,
    SUM(status = 'Successful') Closed 
FROM table_details
WHERE DATE(created_on) BETWEEN '20160701' AND '20160901'