分组统计每组的完成比例

需求:任务有类型、状态(完成和其他几种状态)字段。统计每种类型完成任务的比例。
表结构如下:

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.

最佳答案
SELECT sum(status = 5) / count(*) AS per, task_type
  FROM task
 GROUP BY task_type;
1年前 评论
小手冰凉 (楼主) 1年前
小手冰凉 (楼主) 1年前
wxf666 (作者) 1年前
小手冰凉 (楼主) 1年前
wxf666 (作者) 1年前
讨论数量: 8
SELECT sum(status = 5) / count(*) AS per, task_type
  FROM task
 GROUP BY task_type;
1年前 评论
小手冰凉 (楼主) 1年前
小手冰凉 (楼主) 1年前
wxf666 (作者) 1年前
小手冰凉 (楼主) 1年前
wxf666 (作者) 1年前

你是说这样?

SELECT 
    COUNT(t2.task_id)/COUNT(t1.task_id) AS per,
    t1.task_type
FROM task t1
LEFT JOIN task t2 
    ON t1.task_type=t2.task_type 
        AND t2.`status`=5
GROUP BY t1.task_type;

file

1年前 评论
小手冰凉 (楼主) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!