明确题意:

从exam_record数据表中计算所有用户完成SQL类别高难度试卷得分的截断平均值(去掉一个最大值和一个最小值后的平均值)。

问题拆解:

  • 筛选完成了hard试卷的记录,得到表t1。知识点:where
  • 求各个exam_id的平均值(去掉一个最大值和一个最小值后的平均值)知识点:where、group by 、sum、count、round等
    1. 按score过滤,得到有分数的记录。
    2. 按exam_id分组group by exam_id;
    3. 分别对相同exam_id的多条记录求和sum,然后减去max和min,得到去掉一个最大值和一个最小值后的总分。count(*)得到的结果也需要减去2,然后得到截断后的平均值clip_avg_score,得到表t2
  • t1和t2做inner join计算,用exam_id关联。round(num,m)是把num做四舍五入保留m位小数。
    1. 查询出需要的三个字段,即得到结果。


代码实现:

select 
t1.tag,
t1.difficulty,
t2.clip_avg_score
from 
(
SELECT * from examination_info where difficulty = 'hard' and tag='SQL'
)t1 
join (
select 
    exam_id,
    round((sum(score) - max(score) - min(score))/(count(*)-2),1) as clip_avg_score
    from exam_record 
    where score is not null 
    group by exam_id 
)t2 
on t1.exam_id = t2.exam_id ;

不足之处欢迎指正。