架构:
Student (snum: integer,
sname: char(30),
major: char(25),
level: char(2),
age: integer)
Faculty (fid: integer,
fname: char(30),
deptid: integer)
Class (cname: char(40),
meets_at: char(20),
room: char(10),
fid: integer | fid REFS Faculty.fid)
Enrolled (snum: integer,
cname: char(40) | snum REFS student.snum,
cname REFS class.name)
问题:
P1。找教师,教授最大人数的部门的名称 不同的类。
P2。查找所有课程的名称及其注册人数超过5的注册人数。
我的尝试:
#P1:
select distinct f.fname,max(distinct c.cname)
from faculty f,class c
where Exists (select c.fid,max(distinct c.cname) as myCount
from class c where
f.fid=c.fid);
#P2:
select distinct c.cname
from class c
where Exists (select c.cname
from enrolled e where
e.cname=c.cname and count(e.cname)>5);
但是这给了我错误。请帮帮我。
答案 0 :(得分:0)
问题#1 :只需group by
select f.fname, COUNT(distinct c.cname)
from faculty f
join class c
on f.fid = c.fid
group by f.fname
order by COUNT(distinct c.cname) DESC
limit 1
使用相关查询:
Corraleted v1:
SELECT *
FROM faculty f
WHERE f.id = (SELECT c.fid
FROM class c
GROUP BY c.fid
ORDER BY COUNT(distinct c.cname) DESC
LIMIT 1)
Corraleted v2:
SELECT *
FROM (
SELECT f.*, (SELECT COUNT(distinct c.cname)
FROM class c
WHERE c.fid = f.id) as total
FROM faculty f
) T
ORDER By Total DESC
LIMIT 1
答案 1 :(得分:0)
对于P2,您可以使用连接执行此操作,而不使用嵌套查询。仅在HAVING子句中,WHERE子句中不允许对聚合函数执行条件。您还必须先对类名进行分组。
var map = new ALKMaps.Map("map");
for (var c in map.controls) {
if (map.controls[c].CLASS_NAME == "ALKMaps.Control.KeyboardDefaults")
map.controls[c].deactivate();
}
执行共同相关的嵌套查询,请尝试以下方法:
SELECT C.name, count(*) as enrollment
FROM Class C INNER JOIN Enrolled E
ON C.cname=E.cname
GROUP BY C.name
HAVING count(*) > 5;