sql其他常用操作之空值处理

本文介绍了如何将SQL查询中的子查询转换为更高效的直接SELECT语句,通过两个实际的题目示例展示了如何处理NULL值、计算平均值及时间差,并在HAVING和GROUP BY子句中应用条件。这些技巧对于提升数据库查询性能至关重要。
摘要由CSDN通过智能技术生成

文章目录

题目1

https://www.nowcoder.com/practice/69fc2b1df4144c0991e4b8280d8aba27?tpId=240&tags=&title=&difficulty=0&judgeStatus=0&rp=0

先以子表写法:

select 
    exam_id,
    sum(incomplete) as incomplete_cnt,
    round(sum(incomplete) / count(1), 3)  as incomplete_rate
from 
    (select exam_id, if(score is null, 1, 0) as incomplete
     from exam_record
    ) as t
group by exam_id
having incomplete_cnt >= 1

再根据子表写法的思路改写,直接select一步到位:

select 
    exam_id,
    sum(if(score is null, 1, 0)) as incomplete_cnt,
    #sum(case when score is null then 1 else 0 end) as incomplete_cnt, 
    round(sum(if(score is null, 1, 0)) / count(start_time), 3) as incomplete_rate 
from exam_record
group by exam_id
having incomplete_cnt >= 1

题2

https://www.nowcoder.com/practice/bb474c6cbd77478fb6d9fc86934d0ebb?tpId=240&tags=&title=&difficulty=0&judgeStatus=0&rp=0

select 
    uid,
    round(avg(new_score), 0) as avg_score,
    round(avg(cost_time), 1) as avg_time_took
from 
    (select
         er.uid,
         if(score is not null, score, 0) as new_score,
         if(submit_time is not null, TIMESTAMPDIFF(minute, start_time, submit_time), duration) as cost_time
     from 
         user_info join exam_record as er using(uid) 
         join examination_info using(exam_id)
     where  level=0 and difficulty="hard"
    ) as new_table
group by uid

再利用子表的思路,整理一下,实现不用子表的直接select一步到位的sql代码:

select 
    uid,
    round(avg(if(score is not null, score, 0)), 0) as avg_score,
    round(avg(if(submit_time is not null, TIMESTAMPDIFF(minute, start_time, submit_time), duration)), 1) as avg_time_took
from 
    user_info join exam_record as er using(uid) 
    join examination_info using(exam_id)
where  level=0 and difficulty="hard"
group by uid
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值