分组统计每组的完成比例
需求:任务有类型、状态(完成和其他几种状态)字段。统计每种类型完成任务的比例。
表结构如下:
CREATE TABLE `task` (
`task_id` bigint(20) NOT NULL AUTO_INCREMENT,
`task_type` int(11) DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`task_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=161 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;
数据如下:
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (1, 1, 1);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (2, 2, 1);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (3, 2, 0);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (4, 2, 2);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (5, 3, 0);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (6, 4, 4);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (7, 5, 0);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (8, 5, -1);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (9, 5, 0);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (10, 5, 0);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (11, 5, 0);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (12, 5, 0);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (13, 5, 0);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (14, 5, 0);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (15, 5, 0);
INSERT INTO `task` (`task_id`, `task_type`, `status`) VALUES (16, 5, 5);
状态等于5表示完成
目前的查询sql如下:
SELECT
COUNT( 1 ) / ( SELECT COUNT( 1 ) FROM task WHERE task_type = a.task_type GROUP BY task_type ) AS per,
task_type FROM task a WHERE `status` = 5 GROUP BY task_type;
查询结果:
只有类型等于5的有完成的记录,所以只查出来该类型的完成比例。我想没有完成的任务类型的比例统计成0,要怎么写sql?请大佬赐教
talk is cheap, show me the code.