使用嵌套子查询获取具有多个条件的值

Use nested subquery to fetch value with multiple condition

我有一个 table 名为 test_plan (id, unit, num) 我插入了一些值

INSERT INTO `test_plan` (`id`, `unit`, `num`) VALUES 
('1', '1', '12'),
('2', '1', '13'),
('3', '1', '14'),
('4', '1', '10'),
('5', '2', '10'),
('6', '2', '9'),
('7', '2', '-1'),
('8', '2', '-1'),
('9', '2', '-1'),
('10', '3', '-1'),
('11', '3', '-1'),
('12', '3', '-1');

num 不等于 -1 时,我必须获取单位是每个单位占总单位的分数 i.e.after 运行 它显示为单元 1 的查询已完成 100%,单元 2 已完成 40%,单元 3 已按行完成 0%。我可以计算每个单元的数量,但不能计算完成的数量。

我为此尝试了 JOIN

SELECT a.unit, numb / count(*) as frac FROM test_plan as a 
LEFT OUTER JOIN (SELECT unit, count(num) as numb FROM test_plan where num != -1 group by unit) as b 
ON a.unit = b.unit group by a.unit;

试试这个:

select unit, 
    (sum(case when num = -1 then 0 else 1 end) / count(*)) * 100 as pct_complete
from lecture_plan group by unit;

不需要嵌套子查询,聚合和case语句的结合就足够了