这是我的student_attendance表:
id_student | Id_subject | subject_type | subject_description | total | attendance |date
124 34 Practicals PHY-I 9 9 2014-07
124 34 Practicals PHY-I 9 9 2014-08
124 34 Theory PHY-I 9 9 2014-07
124 34 Theory PHY-I 11 11 2014-08
124 35 Practicals CHEM-I 15 15 2014-07
124 35 Practicals CHEM-I 9 9 2014-08
124 35 Theory CHEM-I 7 9 2014-07
124 35 Theory CHEM-I 13 14 2014-08
124 36 Theory MAT-I 18 18 2014-07
124 36 Theory MAT-I 15 15 2014-08
这是我的主题表:
id_subject | subject_description
34 PHY-I
35 CHEM-I
36 MAT-I
其中id_subject是此表的主键。
这是我的subject_timetable表
id_subject | subject_type
34 Practicals
34 Theory
35 Practicals
35 Theory
36 Theory
student_attendance表和subject_timetable表没有主键。
现在,我希望每个科目(理论和实践)分别为每个科目提供两个月(即2014年7月和8月)的出勤率和总人数。
请帮助我获得合适的查询。 我曾经尝试过这个查询,但是在总结之后它会给某些科目带来错误的结果。
我的MYSQL查询:
SELECT sa.id_student, sa.id_subject, sa.subject_type,
sub.subject_description, sum(sa.total) as sum,sum(sa.attendance) as attendance
FROM (student_attendance AS sa, subject AS sub, subject_timetable AS st)
WHERE sa.id_division =7
AND sa.date BETWEEN "2014-07-01" AND "2014-08-01"
AND sa.id_student = 124
AND sa.id_subject = st.id_subject
AND sa.subject_type = st.subject_type
AND st.id_subject = sub.id_subject
group by sa.id_student,sa.subject_type, sa.id_subject
ORDER BY `sa`.`id_student` ASC
我得到的结果是
id_student | Id_subject | subject_type | subject_description | total | attendance
124 34 Practicals PHY-I 18 18
124 34 Theory PHY-I 20 20
124 35 Practicals CHEM-I 39 39
124 35 Theory CHEM-I 20 23
124 36 Theory MAT-I 48 48
正如您在结果表中所见,7月和8月的CHEM-I(实用)出勤率为9& 15,它的总和达到了24,但在我的结果表中它达到了39,同样的事情发生在MAT-I主题上。