我有一個Sql查詢的問題。因此,我的第一份工作表的結構:使用Sql查詢的全外部聯接
表結構 - StudentGrade
ID - Department - StudentID - Grade - Course
--------------------------------------------
1 2 2002 A+ 102
2 2 2002 B+ 102
3 2 2002 A+ 104
我應該得到的輸出如下:
ID - Department - StudentID - Grade - Course
----------------------------------------------
2 2 2002 B+ 102 // as this was inserted last
3 2 2002 A+ 104
我利用所獲得的上述結果以下查詢只有在存儲在StudentGrade
表中的結果存在時才能正常工作:
SELECT
COALESCE(m.Grade, 'Not Graded Yet') AS Grade
FROM
StudentGrade m
FULL OUTER JOIN
EnrollCourse k ON k.Course = m.Course
WHERE
m.ID IN (SELECT MAX(m.ID)
FROM StudentGrade m
GROUP BY m.StudentID, m.Course)
AND m.StudentID = 2002 // this query returns the grade that is inserted lastly for a course and for a specific student
順便說一句,爲EnrollCourse
表結構如下:
ID - StudentID - Course - EnrollDate
-------------------------------------
1 2002 102 NULL
2 2002 104 NULL
的結果是合格的在校生我的意思是在一門課程註冊學生。所以現在我的要求是,假設StudentID 2002被註冊了兩門課程。如果無級分配給學生,然後輸出 我從StudentGrade
表期待:
ID - Department - StudentID - Grade - Course
------------------------------------------------------
1 2 2002 No Grade Yet 102
2 2 2002 No Grade Yet 104
如果分配的過程102,那麼這將是如下:
ID - Department - StudentID - Grade - Course
---------------------------------------------------
1 2 2002 B+ 102
2 2 2002 No Grade Yet 104
同樣,如果課程成績就像是A +更新,那麼這將是:
ID - Department - StudentID - Grade - Course
------------------------------------------------------
1 2 2002 A+ 102
2 2 2002 No Grade Yet 104
有查詢一些INNER JOIN
。所以我試圖用下面(只是修改了上面,這似乎是不工作):
SELECT
COALESCE(m.Grade, 'Not Graded Yet') AS Grade
FROM
StudentGrade m
FULL OUTER JOIN
EnrollCourse k ON k.Course = m.Course
WHERE
m.ID IN (SELECT MAX(m.ID)
FROM StudentGrade m
FULL OUTER JOIN EnrollCourse k ON k.Course = m.Course
GROUP BY m.StudentRegNo, m.Course)
AND m.StudentID = 2002
當FULL OUTER JOIN,移動從哪裏開來獲得真正的外部表的條件聯接結果。 (現在m是「內連接」。)在你的情況下,用AND替換WHERE。 – jarlh