0

我正在尝试选择学生以及他们每个人的注册人数。因此,如果学生根本没有注册任何课程,我想显示 0 或无。在我可以这样做之前,我希望该行返回 null,但它没有发生。它给了我正确的结果,除了我没有为空的行。

SELECT s.STUDENT_ID, z.COURSE_NO, e.ENROLL_DATE, COUNT(*) AS ENROLLED
FROM STUDENT s,ENROLLMENT e, SECTION z
WHERE s.STUDENT_ID = e.STUDENT_ID
AND e.SECTION_ID = z.SECTION_ID
AND s.PHONE LIKE '702%'
GROUP BY s.STUDENT_ID, z.COURSE_NO, e.ENROLL_DATE

因此,如果它确实为没有参加任何课程的学生返回 null 我想做这样的事情

SELECT lt.STUDENT_ID,lt.FIRST_NAME, lt.LAST_NAME, NVL(COUNT(ENROLLED), 0) AS ENROLLED
FROM STUDENT lt
LEFT OUTER JOIN
(SELECT s.STUDENT_ID, z.COURSE_NO, e.ENROLL_DATE, COUNT(*) AS ENROLLED
FROM STUDENT s,ENROLLMENT e, SECTION z
WHERE s.STUDENT_ID = e.STUDENT_ID
AND e.SECTION_ID = z.SECTION_ID
AND s.PHONE LIKE '702%'
GROUP BY s.STUDENT_ID, z.COURSE_NO, e.ENROLL_DATE) rt
ON lt.STUDENT_ID = rt.STUDENT_ID
GROUP BY lt.STUDENT_ID,lt.FIRST_NAME, lt.LAST_NAME;

如何获得返回 null 的行?

4

1 回答 1

3

使用LEFT [OUTER] JOIN

SELECT s.STUDENT_ID, z.COURSE_NO, e.ENROLL_DATE, COUNT(*) AS ENROLLED
FROM   STUDENT         s
LEFT   JOIN ENROLLMENT e ON e.STUDENT_ID = s.STUDENT_ID 
LEFT   JOIN SECTION    z ON z.SECTION_ID = e.SECTION_ID
WHERE  s.PHONE LIKE '702%'
GROUP  BY s.STUDENT_ID, z.COURSE_NO, e.ENROLL_DATE

语言参考中的详细信息。

于 2013-11-08T20:26:37.447 回答