1
2
3
4
5
6
7
8
9
10
11
select s.dname,s.sname,s.avggrade
from
(select t.dname,t.sname,t.avggrade,row_number() over (partition by t.dname order by t.avggrade desc) rn
from
(select a.name dname,b.name sname,avg(c.grade) avggrade
from
department a,student b,takes c
where a.department_id=b.department_id
and b.student_id=c.student_id
group by a.name,b.name) t) s
where s.rn=1
包含并列的情况,如果一个学院有两个第一,两个人都显示,以上为 sqlserver或oracle写法,其他数据库执行不了
-------------补充-----------
给你个通用的
select s2.*
from
(select t.dname,max(t.avggrade) avggrade
from
(select a.name dname,b.name sname,avg(c.grade) avggrade
from
department a,student b,takes c
where a.department_id=b.department_id
and b.student_id=c.student_id
group by a.name,b.name) t
group by t.dname) s1,
(select a.name dname,b.name sname,avg(c.grade) avggrade
from
department a,student b,takes c
where a.department_id=b.department_id
and b.student_id=c.student_id
group by a.name,b.name) s2
where s1.dname=s2.dname
and s1.avggrade=s2.avggrade