在SQL中获得不需要的输出

时间:2018-11-08 21:28:24

标签: sql

我是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,因为只有第一次注册的科目才在该列中具有考试日期值)。但是我坚持这样做。有什么建议吗?

1 个答案:

答案 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()