题解 | 两种解法 |个人笔记

存在绩点大于该校平均绩点时的学生信息

https://www.nowcoder.com/practice/860fb125c6ac49b080766040f3bd902f

1 开窗聚合函数

知识点:开窗聚合函数——将聚合函数 sum() count() avg() max() min() 与聚合函数 over() 连用,可以动态计算在指定窗口内的各种聚合函数值。

思路:将需要的字段和每个学校平均绩点查询出来建立为新表,再从新表中取出 device_id, university 字段,并筛选出绩点大于该校平均绩点,且该校平均绩点大于3.6符合题意的数据,最后进行排序。

select device_id, university
from 
  (
    select device_id, 
           university, 
           gpa,
           avg(gpa)over(partition by university) avg_gpa
    from user_profile
    group by university, gpa, device_id
  ) a
where gpa > avg_gpa and avg_gpa > 3.6
order by device_id desc

2 join 连接

思路:先查询出每个学校的平均绩点并且平均绩点大于3.6,再将该表连接到原表上,使原表中的gpa去跟每个学校的平均绩点avg_gpa作比较,筛选出绩点大于该校平均绩点的数据,最后排序。

select a.device_id, a.university
from user_profile a
  left join (
    select university, avg(gpa) avg_gpa
    from user_profile
    group by university
    having avg(gpa) > 3.6
  ) b on a.university = b.university
where a.gpa > b.avg_gpa
order by device_id desc

SQL解题笔记 文章被收录于专栏

记录解题过程中遇到的问题、出现的错误以及掌握不牢固的知识点

全部评论
聚合窗口函数那里不用group by也可以的
3 回复 分享
发布于 2023-07-08 19:29 上海
select device_id, a.university from( select university, avg(gpa) as avg_gpa from user_profile group by university having avg_gpa>3.6 ) as a left join user_profile as up on up.university=a.university and up.gpa> a.avg_gpa # where up.gpa> a.avg_gpa and up.university=a.university 小伙伴可以帮忙解释一下为什么这样运行后不对吗, where前后Where后区别在哪里啊
点赞 回复 分享
发布于 2023-06-02 18:23 上海

相关推荐

点赞 评论 收藏
分享
评论
6
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务