select s.name, s.id
from student s join takes t on t.id = s.id
where s.name like 'D%'
group by s.name, s.id
having (
select count(distinct c.course_id)
from course c
where c.dept_name = 'History' and c.course_id = t.course_id)>4
order by s.name
我对GROUP BY如何运作感到困惑。我正在努力寻找从历史系开始至少学习5门课程且名字从D开始的学生。
对嵌套子查询不确定......
course(course id, title, dept name, credits)
student(ID, name, dept name, tot_cred)
takes(ID, course_id, sec_id, semester, year, grade)
答案 0 :(得分:1)
您必须另外JOIN
使用course
表格:
select s.name, s.id
from student s
inner join takes t on t.id = s.id
inner join course c on c.course_id = t.course_id
where s.name like 'D%' and c.dept_name = 'History'
group by s.name, s.id
having count(distinct c.course_id) >= 5
WHERE
子句会返回名称以'D'
开始且的所有学生在历史系中选择至少一门课程。 HAVING
子句会过滤掉历史系中任何不同课程的学生。