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