这道题目用到的数据合并之前我比较陌生,所以专门写一下。加深印象。 步骤一、数据合并: 刚看到题目的时候,大概就知道要用concat或group_concat。但查了一下,发现是两者皆要用。 concat,是以列为单位将数据合并。 group_concat,是以行为单位将数据合并。所以concat在括号内,先将单元格的数据按题意进行合并。 group_concat在括号外,将合并好的单元格按行合并。 但要注意要将数据按天简单处理下。以及使用ORDER BY 排序(题目没说,但测试输出的样式是排列的),将符号分隔符替换。 步骤二、数据运算 略过 步骤三、按要求写条件

太长不看版: 坑点1:数据合并时的符号要替换对。同时记得使用distinct 坑点2:有测试用例有分值不为空,答题时间为空的情况。(我觉得题目这里表述不清晰,没有明确完成或未完成) 坑点3:按未完成数有多到少(这个好判断) 坑点4:有效用户的定义

写在错误之前,在提交前,因为group by 内缺少distinct,一直无法通过测试用例,
参考大佬们的答案发现了问题,修正后通过了用例,兴冲冲的提交,于是,啪一下——

产生了错误1:
select uid,
sum(if(score is null,1,0)) incomplete_cnt,
sum(if(score is not null ,1 ,0)) complete_cnt,
group_concat(distinct concat(date_format(start_time,'%Y-%m-%d'),":",tag)
             order by start_time  SEPARATOR ';') detail
from exam_record e1
left join examination_info e2
 on e1.exam_id =e2.exam_id
 where start_time like '2021%'
 group by uid
 
having incomplete_cnt>1
order by incomplete_cnt desc
回过头来看题目,发现题目内有一个限制条件,叫有效用户。于是我立马在having中补充上条件,
一点测试,通过用例,我立马又兴冲冲的点击提交,啪一下——

产生了错误2
select uid,
sum(if(score is null,1,0)) incomplete_cnt,
sum(if(score is not null ,1 ,0)) complete_cnt,
group_concat(distinct concat(date_format(start_time,'%Y-%m-%d'),":",tag)
             order by start_time  SEPARATOR ';') detail
from exam_record e1
left join examination_info e2
 on e1.exam_id =e2.exam_id
 where start_time like '2021%'
 group by uid
 
having incomplete_cnt>1 and incomplete_cnt <5
and complete_cnt>=1
 order by incomplete_cnt desc
这一次我懵了,我的语句查出的数据比测试用例小,于是盲猜我可能漏了些条件。把测试代码复制进工作台,看了一眼数据有偏差的那个用户。发现,用户分值not null,但是交卷时间(submit_time) is null

于是最后一次调整了求和的逻辑条件。终于成功了。
select uid,
sum(if(submit_time is null,1,0)) incomplete_cnt,
sum(if(submit_time is not null ,1 ,0)) complete_cnt,
group_concat(distinct concat(date_format(start_time,'%Y-%m-%d'),":",tag)
             order by start_time  SEPARATOR ';') detail
from exam_record e1
left join examination_info e2
 on e1.exam_id =e2.exam_id
 where start_time like '2021%'
 
 group by uid
 
having incomplete_cnt>1 and incomplete_cnt <5
and complete_cnt>=1
 order by incomplete_cnt desc