我需要列出一个专业列表和一个字母等级列表,并且需要获得与该字母等级相关的专业内完成的课程数量。所以,如果我有:
Major
Mechanical Engineer
Electrical Engineer
Civil Engineer
Chemical Engineer
...
Grade
A
B
C
...
Student
100 - Alice - Mechanical Engineer
101 - Tom - Mechanical Engineer
102 - Rex - Mechanical Engineer
103 - Bob - Mechanical Engineer
104 - John - Civil Engineer
105 - Alex - Electrical Engineer
Course
001 - Solid Mechanics - 100 - A
002 - Thermodynamics - 100 - A
003 - Heat Transfer - 100 - A
004 - Heat Transfer - 101 - A
005 - Gadgetry - 100 - A
006 - Gadgetry - 101 - A
007 - Gadgetry - 102 - A
008 - Dynamics - 102 - A
009 - Gadgetry - 101 - C
010 - Heat Transfer - 102 - C
011 - Fluid Mechanics - 100 - B
012 - Materials - 102 -B
013 - Intro to EE - 105 - B
014 - Embedded Systems - 105 - B
015 - Analog Circuits - 105 - B
...
我需要输出:
Mechanical Engineer - A - 8
Mechanical Engineer - B - 2
Mechanical Engineer - C - 2
Electrical Engineer - A - 0
Electrical Engineer - B - 3
...
[还有一张学生用桌,说明每个学生所在的专业,课程表上该学生上哪门课程(有些学生不能上任何课程),以及从那门课程获得的分数。
到目前为止,我有:
SELECT major_name, grade, COUNT(grade_code) OVER (PARTITION BY major_name)
FROM Major CROSS JOIN ((grade LEFT JOIN course USING (grade_code)) RIGHT JOIN student USING (st_id))
ORDER BY major_name, grade;
但是该计数不起作用(每个专业都得到相同的不正确计数),实质上是课程表中字母等级的总计数。
Mechanical Engineer - A - 10
Mechanical Engineer - B - 10
Mechanical Engineer - C - 10
Electrical Engineer - A - 10
...
不需要CROSS JOIN
或合计COUNT...OVER()
窗口功能。只需联接主表(student和course),然后联接查找表(major和grade)。然后,合计计数。因为major链接到不在FROM
子句中的student,所以用相应的别名替换传统USING
的ON
:
SELECT m.major_name,
g.grade,
count(*) as major_grade_count
FROM course c
LEFT JOIN student s USING (st_id)
LEFT JOIN grade g USING (grade_code)
LEFT JOIN major m ON g.major_code = m.major_code -- ADJUST FIELD HERE
GROUP BY m.major_name,
g.grade;