SQL128未完成试卷数大于1的有效用户

 请统计2021年每个未完成试卷作答数大于1的有效用户的数据(有效用户指完成试卷作答数至少为1且未完成数小于5),输出用户ID、未完成试卷作答数、完成试卷作答数、作答过的试卷tag集合,按未完成试卷数量由多到少排序。

一、知识点

1、substring

substring(str, pos):        substring(被截取字段,从第几位开始截取)

substring(str, pos, length):        substring(被截取字段,从第几位开始截取,截取长度)

2、concat

concat(str1,str2,...) 

SELECT CONCAT('My', 'S', 'QL')
#结果是MySQL

concat_ws(‘拼接符’,str1,str2,...) 

concat_ws(‘_’,My,S,Q,L) 
#结果是My_S_Q_L

group_concat( [distinct] 要连接的字段 [order by 排序字段 asc/desc ] [separator '分隔符'])

将多行合并成一行


二、题目分析

1、条件

2021年每个未完成试卷作答数大于1的有效用户的数据(有效用户指完成试卷作答数至少为1且未完成数小于5)

2021用where:

where year(start_time)=2021

未完成试卷做答数及完成试卷作答数用sum函数统计:

sum(if(submit_time is null,1,0)) as incomplete_cnt,
sum(if(submit_time is null,0,1)) as complete_cnt

未完成试卷作答数大于1用having筛选:

having incomplete_cnt>1

有效用户用having筛选:

having complete_cnt>=1 and incomplete_cnt<5

2、输出结果

detail中是1002作答过的试卷{日期:tag}集合,日期和tag间用:连接,多元素间用;连接

group_concat(distinct concat_ws(':',substring(start_time,1,10),tag) separator ';')

3、完整代码

select uid,
sum(if(submit_time is null,1,0)) as incomplete_cnt,
sum(if(submit_time is null,0,1)) as complete_cnt,
group_concat(distinct concat_ws(':',substring(start_time,1,10),tag) separator ';') as detail
from exam_record as a
join examination_info as b on a.exam_id=b.exam_id
where year(start_time)=2021
group by uid
having complete_cnt>=1 and incomplete_cnt<5 and incomplete_cnt>1
order by incomplete_cnt desc

欢迎探讨

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值