现有三张表:学生信息表,班级信息表,考试成绩表
三表字段如下:
学生信息表:stid ,bjid,stname,stsex,stage
班级信息表:bjid,bname
考试成绩表:chengjid,stid,kclx(课程类型),chengj(各科成绩)
问题:怎么查询总分700以下最高分数的学生和其所在的班级
,
楼上这个专家的sql错的地方太多了。
最直白的写法,先用having限制数据范围,然后取max得到检索条件,再去查原表就行了
select a.*, b.*
from 学生信息表 a, 班级信息表 b
where a.bjid = b.bjid
and a.stid in
(select stid
from 考试成绩表
group by stid
having sum(chengji) = (select max(sum(chengji))
from 考试成绩表
group by stid
having sum(chengji) < 700));
但特么谁这么写我就跟谁急。
如果使用开窗函数,可以让这个变得简单,由于不清楚你的oracle版本,我只能写个老版本能用的,如果是新版本会更简单,新版本里可以多重聚合
select *
from (select a.stid,
a.stname,
a.stsex,
a.stage,
b.bname,
rank() over(order by chengji desc) rk
from (select stid, sum(chengji) chengji
from 考试成绩表
group by stid
having sum(chengji) < 700) c)
where rk = 1;
然后,在12c以上,甚至都不需要使用嵌套
select a.stid,
max(a.stname) stname,
max(a.stsex) stsex,
max(a.stage) stage,
max(b.bname) bname,
sum(c.chengji) cj
from 学生信息表 a, 班级信息表 b, 考试成绩表 c
where a.bjid = b.bjid
and a.stid = c.stid
group by a.stid
having sum(c.chengji) < 700
order by 6 desc
fetch first 1 row only;
select stid ,bjid,stname,stsex,stage,(select sum(chengj) from 考试成绩表 where s.stid=stid group by stid) score from 学生信息表 s
where score<700 and rownum = 1 order by score desc;