我有一张表,如:
mysql> select RefID,State,StartTime,EndTime from execReports limit 5; +--------------------------------------+-----------+---------------------+---------------------+ | RefID | State | StartTime | EndTime | +--------------------------------------+-----------+---------------------+---------------------+ | 00019a52-8480-4431-9ad2-3767c3933627 | Completed | 2016-04-18 13:45:00 | 2016-04-18 13:45:01 | | 00038a8a-995e-4cb2-a335-cb05d5b3e92d | Aborted | 2016-05-03 04:00:00 | 2016-05-03 04:00:02 | | 001013f8-0b86-456f-bd59-a7ef066e565f | Completed | 2016-04-14 03:30:00 | 2016-04-14 03:30:11 | | 001f8d23-3022-4271-bba0-200494de678a | Failed | 2016-04-30 05:00:00 | 2016-04-30 05:00:02 | | 0027ba42-1c37-4e50-a7d6-a4e24056e080 | Completed | 2016-04-18 03:45:00 | 2016-04-18 03:45:02 | +--------------------------------------+-----------+---------------------+---------------------+
我可以用以下内容提取每个州的执行计数:
mysql> select distinct State,count(StartTime) as nbExec from execReports group by State; +-----------+--------+ | State | nbExec | +-----------+--------+ | Aborted | 3 | | Completed | 14148 | | Failed | 49 | +-----------+--------+ 4 rows in set (0.02 sec)
我可以用以下方法提取每周的执行计数:
mysql> select distinct extract(week from StartTime) as Week, count(StartTime) as nbExec from execReports group by Week; +------+--------+ | Week | nbExec | +------+--------+ | 14 | 1317 | | 15 | 3051 | | 16 | 3066 | | 17 | 3059 | | 18 | 3059 | | 19 | 652 | +------+--------+ 6 rows in set (0.01 sec)
但我想提取一个交叉表,如:
+------+---------+-----------+--------+---------+---------+ | Week | nbExec | Completed | Failed | Running | Aborted | +------+---------+-----------+--------+---------+---------+ | 14 | 1317 | 1312 | 3 | 1 | 1 | | 15 | 3051 | 3050 | 1 | 0 | 0 | | 16 | 3066 | 3060 | 3 | 2 | 1 | | 17 | 3059 | 3058 | 0 | 1 | 0 | | 18 | 3059 | 3057 | 1 | 0 | 1 | | 19 | 652 | 652 | 0 | 0 | 0 | +------+---------+-----------+--------+---------+---------+
我被困在这几天了。任何帮助表示赞赏。
祝你好运
答案 0 :(得分:2)
select extract(week from StartTime) as Week, count(StartTime) as nbExec,
sum(if(state="Completed",1,0)) Completed,
sum(if(state="Failed",1,0)) Failed,
sum(if(state="Aborted",1,0)) Aborted
from execReports group by Week;
答案 1 :(得分:0)
您可以为此加入多表。如果您想要动态行到列,请选中:MySQL pivot row into dynamic number of columns
SELECT
a.week,
count(a.StartTime) as nbExec,
count(b1.StartTime) as Completed,
count(b2.StartTime) as Failed,
count(b3.StartTime) as Running,
count(b4.StartTime) as Aborted,
FROM execReports a
LEFT JOIN execReports b1 ON a.refID = b1.refID and b1.state ='Completed'
LEFT JOIN execReports b2 ON a.refID = b2.refID and b2.state ='Failed'
LEFT JOIN execReports b3 ON a.refID = b3.refID and b3.state ='Running'
LEFT JOIN execReports b4 ON a.refID = b4.refID and b4.state ='Aborted'
GROUP BY 1