SUM DISTINCT MYSQL |在哪里条款

时间:2013-10-18 05:22:24

标签: mysql sum distinct

我想根据表格(历史记录)中的SUM获得结果,其中用户名包含“红色”并按月分组。这里是查询:

select month(date),
SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) as total_sucess, 
SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END) as total_failed
from history
where date between '201305%' AND '201311%'  AND username like '%@red%' 
GROUP BY month(history.date);

结果:

+------------+--------------+--------------+
| month(date) | total_sucess | total_failed |
+------------+--------------+--------------+
|          5 |        10960 |         3573 |
|          6 |         2336 |         1202 |
|          7 |         2211 |         1830 |
|          8 |         5312 |         3125 |
|          9 |         9844 |         5407 |
|         10 |         6351 |         3972 |
+------------+--------------+--------------+

问题是,如何获得不同的total_success和total_failed SUM?只是在一个查询?

我尝试过使用此

select month(tgl),
SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) as total_sucess, 
SUM(DISTINCT (username) CASE WHEN status='success' THEN 1 ELSE 0 END) as distinct_total_sucess, 
SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END) as total_failed,
SUM(DISTINCT (username) CASE WHEN status='failed' THEN 1 ELSE 0 END) as distinct_failed_sucess
from history_auth
where tgl between '201305%' AND '201311%'  AND username like '%@t.sel%' 
GROUP BY month(history_auth.tgl);

但是得到错误sql语法...我不知道这个:(

1 个答案:

答案 0 :(得分:3)

我能满足您的要求的最佳方案是您希望每月成功/失败的不同用户名数量。

如果是这样,我认为你需要一对子选择来获得这些数据。

重新调整查询(添加另一个子选择以获得6个月,而不是依赖于所有月份的代表。

SELECT Sub1.aMonth,
SUM(CASE WHEN history.status='success' THEN 1 ELSE 0 END) as total_sucess, 
SUM(CASE WHEN history.status='failed' THEN 1 ELSE 0 END) as total_failed,
IFNULL(SuccessCount, 0),
IFNULL(FailedCount, 0)
FROM 
(
    SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 0 MONTH)) AS aMonth 
    UNION SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 1 MONTH)) 
    UNION SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 2 MONTH)) 
    UNION SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 3 MONTH))
    UNION SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 4 MONTH))
    UNION SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 5 MONTH)) 
    UNION SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 6 MONTH))
) Sub1
LEFT OUTER JOIN history 
ON MONTH(history.date) = Sub1.aMonth
AND username LIKE '%@red%' 
LEFT OUTER JOIN
(
    SELECT MONTH(date) AS aMonth, COUNT(DISTINCT username) AS SuccessCount
    FROM history
    WHERE status='success'
    AND username LIKE '%@red%' 
    GROUP BY MONTH(date)
) Sub2
ON Sub1.aMonth = Sub2.aMonth
LEFT OUTER JOIN
(
    SELECT MONTH(date) AS aMonth, COUNT(DISTINCT username) AS FailedCount
    FROM history
    WHERE status='failed'
    AND username LIKE '%@red%' 
    GROUP BY MONTH(date)
) Sub3
ON Sub1.aMonth = Sub3.aMonth
GROUP BY Sub1.aMonth, SuccessCount, FailedCount