mysql中的Having子句中的case语句

时间:2015-03-11 05:41:48

标签: mysql sql

我有一个存储过程,我必须在运算符的基础上检查比较一些结果。运营商可以是&#39; >&#39;或者&#39; <&#39; 我的查询是:

  SELECT COUNT(LastWeekId) , COUNT(PreviousToLastWeekId)
        FROM 
        (
        SELECT `transaction_id`  AS LastWeekId, NULL AS PreviousToLastWeekId
        FROM `kwt_transaction`
        WHERE `statusid` =1000            
        AND (createdon BETWEEN CONCAT(DATE_SUB(DATE(NOW()), INTERVAL 7 DAY)," 00:00:00") AND CONCAT(DATE_SUB(DATE(NOW()), INTERVAL 1 DAY)," 23:59:59"))
    UNION

        SELECT  `transaction_id` AS LastWeekId, NULL AS PreviousToLastWeekId
        FROM `kwt_transactions_p2p`
        WHERE `statusid` =1000            
        AND (createdon BETWEEN CONCAT(DATE_SUB(DATE(NOW()), INTERVAL 7 DAY)," 00:00:00") AND CONCAT(DATE_SUB(DATE(NOW()), INTERVAL 1 DAY)," 23:59:59"))
        UNION                   
        SELECT NULL AS LastWeekId, `transaction_id` AS PreviousToLastWeekId
        FROM `kwt_transaction`
        WHERE `statusid` =1000            
        AND (createdon BETWEEN CONCAT(DATE_SUB(DATE(NOW()), INTERVAL 14 DAY)," 00:00:00") AND CONCAT(DATE_SUB(DATE(NOW()), INTERVAL 8 DAY)," 23:59:59"))
    UNION   
        SELECT NULL AS LastWeekId, `transaction_id` AS PreviousToLastWeekId
        FROM `kwt_transactions_p2p`
        WHERE `statusid` =1000            
        AND (createdon BETWEEN CONCAT(DATE_SUB(DATE(NOW()), INTERVAL 14 DAY)," 00:00:00") AND CONCAT(DATE_SUB(DATE(NOW()), INTERVAL 8 DAY)," 23:59:59"))
    ) ttable
    HAVING COUNT(LastWeekId) > COUNT(PreviousToLastWeekId)

所以我想查一下:

HAVING Case _operaotr
       when '>'    
       COUNT(LastWeekId) > COUNT(PreviousToLastWeekId);
when '<'
    COUNT(LastWeekId) < COUNT(PreviousToLastWeekId);
End Case;

这在mysql中是否可行

1 个答案:

答案 0 :(得分:2)

我认为你可以这样做:

HAVING CASE @Operator
    WHEN '>' THEN COUNT(LastWeekId) > COUNT(PreviousToLastWeekId)
    WHEN '<' THEN COUNT(LastWeekId) < COUNT(PreviousToLastWeekId)
    WHEN '=' THEN COUNT(LastWeekId) = COUNT(PreviousToLastWeekId)
    -- and so on
END