《SQL面试50题》刷题笔记 day8(知识点:左联结、开窗函数lead、case when condition用法)

这篇博客详细记录了在SQL面试中遇到的两个问题,涉及左联结、开窗函数LEAD以及CASE WHEN语句的应用。通过实例解析了如何使用这些函数解决查询所有学生所有课程成绩、各科成绩高低分及率的问题,强调了函数使用中的注意事项和CASE WHEN的不同语法结构。
摘要由CSDN通过智能技术生成

今天依旧不加班,但工作任务重,明天加油吧~~

问题12 按平均成绩由高到低显示所有学生的所有课程的成绩以及平均成绩
方法1(开窗函数)

select a.sid, a.sscore, a.sscore2,a.sscore3,a.avescore
from
(select sid,sscore,
lead(sscore,1) over(partition by sid order by cid) sscore2,
lead(sscore,2) over(partition by sid order by cid) sscore3,
avg(sscore) over(partition by sid) avescore from score) a
group by a.sid 
order by a.avescore desc;

运行结果:

+-----+--------+---------+---------+----------+
| sid | sscore | sscore2 | sscore3 | avescore |
+-----+--------+---------+---------+----------+
| 07  |     89 |      98 |    NULL |  93.5000 |
| 01  |     80 |      90 |      99 |  89.6667 |
| 05  |     76 |      87 |    NULL |  81.5000 |
| 03  |     80 |      80 |      80 |  80.0000 |
| 02  |     70 |      60 |      80 |  70.0000 |
| 04  |     50 |      30 |      20 |  33.3333 |
| 06  |     31 |      34 |    NULL |  32.5000 |
+-----+--------+---------+---------+----------+

在这个例子中,我本来想的是开窗函数构成的表中,取每个sid的第一行数据,因为这一行数据给出了distinct sid的那种感觉,我用了first_value开窗函数,但是发现不对,是我对first_value理解有误,不是这样用的,是排序后选最值这种用途。

方法2(左联结)

select s.sid, s1.sscore score01, s2.sscore score02, s3.sscore score03, a.avescore 
from student s
left join score s1 on s.sid=s1.sid and s1.cid='01'
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值