0
我想根据表(历史)SUM得到的结果,其中用户名包含'红色'并按月分组。在这里查询:SUM DISTINCT MYSQL | WHERE CLAUSE
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次成功和1次失败? – Barmar
发布您的例外结果 –
如果这就是你想要的,你需要编写一个按用户名,状态和月份分组的子查询。 – Barmar