select uid,sum(case when submit_time is null then 1 else 0 end)as incomplete_cnt,sum(case when submit_time is not null then 1 else 0 end) as complete_cnt,group_concat(distinct concat_ws(":",date(start_time),tag) SEPARATOR ';') as detail from exam_record r inner join examination_info e on r.exam_id = e.exam_id where year(start_time)='2021' group by uid having complete_cnt>=1 and incomplete_cnt between 2 and 4 order by incomplete_cnt desc;
题目要求:统计2021年每个未完成试卷作答数大于1的有效用户的数据
从最终要得到的数据中可以提取到结果需要满足的条件:1) 2021年的数据; 2) 未完成试卷作答数大于1;3)有效用户
最终得到的是用户的统计数据,所以需要根据用户进行分组:group by uid
第一个条件需要的是exam_record表的start_time字段,得到where条件:year(start_time)='2021'
第二个条件中需要对未完成试卷的数量作统计,submit_time为空则认为是未完成:sum(case when submit_time is null then 1 else 0 end)as incomplete_cn, 在group中对统计值进行函数判断需要用having,完成试卷数大于一:having complete_cnt>=1
第三个条件中有效用户要求完成试卷作答数至少为1且未完成数小于5,所以需要先统计完成试卷作答数:sum(case when submit_time is not null then 1 else 0 end) as complete_cnt, 完成数和未完成数是统计值且结合条件二,得到条件数:incomplete_cnt between 2 and 4
对分组中的每行数据的两个字段做拼接:concat_ws(":",date(start_time),tag)
对整个分组中的某一个字段做拼接:group_concat(distinct concat_ws(":",date(start_time),tag) SEPARATOR ';')
distinct是为了避免出现一个人在一天考了两场的情况