此查询将输出通过 ExamID 1 和 ExamID 3 的学生的详细信息。我还想显示他们在每门考试中获得的分数。如何?

This query will output the details of students who passed in ExamID 1 and ExamID 3. I want to show the mark they got in each exam also. How?

如何更新下面包含连接和子查询的 sql 查询,以便我可以获得 ExamID=1ExamID= 的标记3也在最后的结果集中?

SELECT DISTINCT st.StudentID,st.Name 
FROM Students st 
INNER JOIN StudentMarks stm ON st.StudentID=stm.StudentID
WHERE st.StudentID IN(SELECT stm.StudentID 
                      FROM StudentMarks stm 
                      INNER JOIN Exam ex ON stm.ExamID=ex.ExamID
                      WHERE stm.Mark>=ex.MinMarkForPass AND stm.ExamID=1
INTERSECT
SELECT stm.StudentID 
FROM StudentMarks stm 
INNER JOIN Exam ex ON stm.ExamID=ex.ExamID
WHERE stm.Mark >= ex.MinMarkForPass AND stm.ExamID=3)

不需要INTERSECT,你可以这样做:

WITH BothCTE
(
    SELECT stm.StudentID 
    FROM StudentMarks stm 
    INNER JOIN Exam ex ON stm.ExamID=ex.ExamID
    WHERE stm.Mark >= ex.MinMarkForPass AND stm.ExamID IN(1, 3)
    GROUP BY StudentID
    HAVING(DISTINCT ExamID) >= 2
)
SELECT st.StudentID, st.Name, stm.Mark
FROM Students st 
INNER JOIN StudentMarks stm ON st.StudentID = stm.StudentID
WHERE st.StudentID IN(SELECT StudentID FROM BothCTE);

CTE会给你那些参加过两次考试的学生,然后你可以把这些结果和分数table结合起来得到学生的分数。