我有一张表格,其中每一行代表一个更正,包括ID,日期和原因
id | date | causes
___________________________________
1 | 2018-01-29 08:49:19 | crash
2 | 2018-08-08 10:03:37 | timeout
3 | 2018-06-26 07:48:12 | other
我使用此sql请求按月获取更正次数
SELECT YEAR(date) Year, MONTH(date) Month, count(*) Total FROM correction group by YEAR(date), MONTH(date)
它给我这样的结果
Year | Month | Total
____________________
2018 | 1 | 42
2018 | 2 | 69
2018 | 3 | 50
是否可以修改请求以获取每种原因的结果数,并得到类似以下结果:
Year | Month | Total | crash | timeout | other
____________________________________________
2018 | 1 | 42 | 10 | 12 | 20
2018 | 2 | 69 | 9 | 50 | 10
2018 | 3 | 50 | 10 | 20 | 20
答案 0 :(得分:1)
您需要条件聚合:
SELECT YEAR(date) Year, MONTH(date) Month, COUNT(*) Total,
SUM(causes = 'crash') crash,
SUM(causes = 'timeout') timeout,
SUM(causes = 'other') other
FROM correction c
GROUP BY YEAR(date), MONTH(date);