對於作業分配,我必須編寫一個MySQL查詢來計算數據庫表中每個學生的GPA。我將問題分解爲三部分:(1)計算每個學生獲得的成績點的數量,(2)計算所採用的學分數量,然後(3)將學分點數除以學分。下面是我的步驟1和2書面查詢:賺在MySQL中處理來自兩個子查詢的結果
計算等級分:
SELECT ID, SUM(credits) AS credits_taken FROM takes NATURAL JOIN course GROUP BY ID
2查找等級分獲得:
SELECT ID, SUM(credits * (SELECT points FROM gradepoint WHERE letter = grade)) AS tot_grade_points
FROM takes NATURAL JOIN course
GROUP BY ID
我手動評估每個查詢並返回正確的結果。但我不知道如何爲每個學生返回(credits_taken/tot_grade_points)
。這是我曾嘗試過的:
SELECT ID, GPA
FROM student AS S NATURAL JOIN
(SELECT ID,('credits_taken'/SUM(credits * (SELECT points FROM gradepoint WHERE letter = grade))) AS GPA
FROM takes AS T1 NATURAL JOIN course
WHERE S.ID = T1.ID
AND EXISTS (
SELECT ID, SUM(credits) AS 'credits_taken'
FROM takes AS T2 NATURAL JOIN course
WHERE S.ID = T2.ID
GROUP BY ID
)
GROUP BY ID) Z
GROUP BY ID
但是,這給了我錯誤「未知的列'S.ID'在'where子句'」。從我讀過的內容來看,不能在聯接操作中引用子查詢中的表的別名。有沒有人有另一種方法來計算這兩個子查詢並將它們返回到學生ID?
'take'表將學生ID映射爲他們所學課程的信息,最重要的是course_id和grade。 「課程」表包含「學分」字段,該課程值得學分。
編輯
下面是相關的表結構:
需要:
Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| ID | varchar(5) | NO | PRI | | |
| course_id | varchar(8) | NO | PRI | | |
| sec_id | varchar(8) | NO | PRI | | |
| semester | varchar(6) | NO | PRI | | |
| year | decimal(4,0) | NO | PRI | 0 | |
| grade | varchar(2) | YES | | NULL | |
+-----------+--------------+------+-----+---------+-------+
課程:
+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| course_id | varchar(8) | NO | PRI | | |
| title | varchar(50) | YES | | NULL | |
| dept_name | varchar(20) | YES | MUL | NULL | |
| credits | decimal(2,0) | YES | | NULL | |
+-----------+--------------+------+-----+---------+-------+
什麼是表格上的ID列,你想加入到Takes叫?它是ID嗎?發佈3個表格的列結構將很有用。 – dash 2012-02-15 20:34:25
從'credits_taken'(這是一個字符串)移除credits_taken/SUM(...)並再試一次。 – 2012-02-15 20:35:55
當我刪除撇號時,它表示'字段列表'中的未知列'credits_taken'。 – Matt 2012-02-15 21:09:21