MySQL的解码功能

时间:2015-06-15 11:20:21

标签: mysql sql decode

我在下面的sql:

SELECT 
    DATE_FORMAT(date_created, '%Y-%m-%d')   AS date_
    , IF(STATUS=1,'Success','Failed')       AS PROCESSED_STATUS
    ,COUNT(1)
FROM 
    x
WHERE 
    DATE_FORMAT(date_created, '%Y-%m-%d') BETWEEN  '2011-01-01' AND '2015-06-04'
GROUP BY 
    DATE_FORMAT(date_created, '%Y-%m-%d')
    , STATUS
ORDER BY 
    DATE_FORMAT(date_created, '%Y-%m-%d') DESC;

实际上格式如下所示

Date_       PROCESSED_STATUS    Count(1)
2015-05-15  Failed              1
2015-05-13  Failed              691
2015-05-13  Success             68
2012-05-19  Failed              346
2012-05-19  Success             28
2012-05-18  Failed              184
2012-05-18  Success             18
2012-05-17  Failed              176
2012-05-17  Success             9
2012-05-16  Failed              425
2012-05-16  Success             49
2012-03-13  Failed              1
2012-02-23  Success             193

但我需要这种格式:

Date_   Failed    Success

并且数据内部将显示失败和成功的日期和计数。

通常在oracle上,我使用解码函数,但我不知道mysql。请帮助:)

2 个答案:

答案 0 :(得分:2)

使用条件聚合:

SELECT DATE_FORMAT(date_created, '%Y-%m-%d') AS date_, 
       SUM(STATUS = 1) as Success,
       SUM(STATUS <> 1 OR STATUS IS NULL) as Failed
FROM x
WHERE DATE_FORMAT(date_created, '%Y-%m-%d') BETWEEN  '2011-01-01' AND '2015-06-04'
GROUP BY DATE_FORMAT(date_created, '%Y-%m-%d')
ORDER BY DATE_FORMAT(date_created, '%Y-%m-%d') DESC;

答案 1 :(得分:0)

将条件移动到COUNT / SUM:

SELECT DATE_FORMAT(date_created, '%Y-%m-%d') AS date_, 
   SUM(CASE WHEN Status=1 THEN 0 ELSE 1 END AS Failed,
   SUM(CASE WHEN Status=1 THEN 1 ELSE 0 END AS Success
FROM x
WHERE DATE_FORMAT(date_created, '%Y-%m-%d') BETWEEN  '2011-01-01' AND '2015-06-04'
GROUP BY DATE_FORMAT(date_created, '%Y-%m-%d')
ORDER BY DATE_FORMAT(date_created, '%Y-%m-%d') DESC;

我使用标准SQL CASE而不是专有的IF / DECODE,因为它是可移植的