左外连接与子查询

时间:2013-11-06 18:23:17

标签: sql oracle left-join

我正在尝试从学生获得成绩的课程中选择课程编号

首先,我选择学生在哪里获得每个grade_type_code的成绩

SELECT z.STUDENT_ID ,m.GRADE_TYPE_CODE,COUNT(*) AS COURSE_NUM
FROM STUDENT z, GRADE m,SECTION s, COURSE w
WHERE z.STUDENT_ID = m.STUDENT_ID
AND m.SECTION_ID = s.SECTION_ID
AND s.COURSE_NO = w.COURSE_NO
GROUP BY z.STUDENT_ID,m.GRADE_TYPE_CODE

比我尝试做左外连接

SELECT COURSE_NO
FROM COURSE lt
LEFT OUTER JOIN
(SELECT z.STUDENT_ID ,m.GRADE_TYPE_CODE,COUNT(*) AS COURSE_NUM
FROM STUDENT z, GRADE m,SECTION s, COURSE w
WHERE z.STUDENT_ID = m.STUDENT_ID
AND m.SECTION_ID = s.SECTION_ID
AND s.COURSE_NO = w.COURSE_NO
GROUP BY z.STUDENT_ID,m.GRADE_TYPE_CODE) rt
ON lt.COURSE_NO = rt.COURSE_NO;

1 个答案:

答案 0 :(得分:2)

select
  c.course_no
from
  course c,
  section s,
  grade g
where
  s.course_no = c.course_no and
  g.section_id = s.section_id
group by
  c.course_no
having
  count(distinct g.grade_type_code) = 
  (select count(distinct grade_type_code) from grade);

http://sqlfiddle.com/#!4/e7826/1/0