我是SQL的新手。我想列出所有主题的所有代码和名称。对于那些首次注册的学生,还列出了推荐的考试日期。
结果集的列顺序:
neptuncode, subjectname, examdate
我运行了以下查询
SELECT
subjects.neptuncode AS "neptuncode",
subjects.subjectname AS "subjectname",
enrollments.examdate AS "examdate"
FROM
subjects
LEFT OUTER JOIN
enrollments ON enrollments.subject = subjects.subject_ID
GROUP BY
subjects.neptuncode, subjects.subjectname, enrollments.examdate
HAVING
COUNT(enrollments.enrollmentdate) = 1
ORDER BY
subjects.neptuncode, subjects.subjectname, enrollments.examdate;
结果仅是学生与neptuncode和考试日期一起首次注册的科目。我还想列出所有带有其neptuncode和Examdate的科目(它应该为NULL,因为只有第一次注册的科目才在该列中具有考试日期值)。但是我坚持这样做。有什么建议吗?
答案 0 :(得分:1)
请您尝试一下
SELECT
subjects.neptuncode AS "neptuncode"
, subjects.subjectname AS "subjectname"
, CASE WHEN COUNT(enrollments.enrollmentdate) = 1 THEN MAX(enrollments.enrollmentdate)
ELSE NULL
END AS "examdate"
FROM subjects
LEFT OUTER JOIN enrollments
ON enrollments.subject = subjects.subject_ID
GROUP BY
subjects.neptuncode
, subjects.subjectname
ORDER BY
subjects.neptuncode
, subjects.subjectname
;
我认为您需要将enrollmentdate
视为一个汇总,因为只允许1个注册日期,所以您可以使用max()
或min()
。