题解 | #根据指定记录是否存在输出不同情况#
根据指定记录是否存在输出不同情况
https://www.nowcoder.com/practice/f72d3fc27dc14f3aae76ee9823ccca6b
#1.计算所有用户的答题完成情况
with t1 as(
select
b.uid,
count(start_time) as total_cnt,
COUNT(start_time)-COUNT(submit_time) as incomplete_cnt,
ROUND((COUNT(start_time)-COUNT(submit_time)) /COUNT(*),3) incomplete_rate,
level
from
exam_record as a
right join(
select
uid,
level
from
user_info
) as b
on a.uid = b.uid
group by uid
order by incomplete_rate asc)
#2.结果1:有满足条件的0级用户
select
uid,
incomplete_cnt,
incomplete_rate
from
t1
where exists(
select
uid
from
t1
where
level = 0
and incomplete_cnt > 2
)and level = 0
union all
#3.结果2:没有满足条件的0级用户,输出所有用户的答题情况
select
uid,
incomplete_cnt,
incomplete_rate
from
t1
where not exists(
select
uid
from
t1
where
level = 0
and incomplete_cnt > 2
)and total_cnt > 0
order by incomplete_rate
这题好几个坑!
(1)第一步的时候我们要建立一个所有用户答题完成情况表。因为有聚合运算,我很自的想到把exam_record作为主表并命名为a,select a.uid这个时候结果是错的,因为题目要求的是所有0级用户的未完成情况,所以要select user_info的所有0级用户id。
而且,计算‘未完成率’的时候,注意检查不管你用哪种公式,分母不能为0否则会返回null!
(2)第二步建立所有0级用户的答题情况表——这一步就简单了,相信大家都没问题
(3)输出所有有作答记录的用户答题情况表(我漏看了这个重要条件),注意这些用户的total_cnt > 0否则我们要过滤掉哦~
tips:这一题两个结果1.2是互斥的,所以用 union 和 union all 都对