下面是一个SQL查询,它计算所选学生已注册的模块上所有学生的平均结果
SELECT DISTINCT
AVG(students_vs_modules.module_result) AS module_average,
students_vs_modules.module_id,
modules.module_name
FROM
students_vs_modules
INNER JOIN
modules ON students_vs_modules.module_id = modules.module_id
WHERE
(students_vs_modules.module_id IN (SELECT module_id
FROM students_vs_modules AS students_vs_modules_1
WHERE (user_id = @user_id)))
AND (students_vs_modules.module_result <> 0)
GROUP BY
students_vs_modules.module_id,
modules.module_name
然后,我在下面的查询中显示了每个模块中特定学生的成绩
SELECT
student_records.f_name, student_records.l_name,
modules.module_name, modules.module_id,
modules.semester, modules.year,
students_vs_modules.module_result,
year.year_title
FROM
student_records
INNER JOIN
students_vs_modules ON student_records.user_id = students_vs_modules.user_id
INNER JOIN
modules ON students_vs_modules.module_id = modules.module_id
INNER JOIN
YEAR ON modules.YEAR = YEAR.year_id
INNER JOIN
exam_session ON students_vs_modules.academic_year = exam_session.academic_year
AND modules.semester = exam_session.semester
WHERE
(student_records.user_id = @user_id)
ORDER BY
modules.YEAR, modules.semester, modules.module_id
有没有办法可以将这两个查询组合在一起,这样我就可以有一个表格,显示学生个人成绩以及班级平均成绩。
所以我可以在我的网站上为个人用户提供一个表格;
module_id | semester | year | module_result | module_average |
--------------------------------------------------------------
答案 0 :(得分:1)
SELECT student_records.f_name,
student_records.l_name,
modules.module_name,
modules.module_id,
modules.semester,
modules.year,
students_vs_modules.module_result,
year.year_title,
ModuleAvgs.module_average
FROM student_records
INNER JOIN students_vs_modules ON student_records.user_id = students_vs_modules.user_id
INNER JOIN modules ON students_vs_modules.module_id = modules.module_id
INNER JOIN (SELECT DISTINCT AVG(students_vs_modules.module_result) AS module_average,
students_vs_modules.module_id
FROM students_vs_modules
INNER JOIN modules ON students_vs_modules.module_id = modules.module_id
WHERE (students_vs_modules.module_id IN
(SELECT module_id
FROM students_vs_modules AS students_vs_modules_1
WHERE (user_id = @user_id)))
AND (students_vs_modules.module_result <> 0)
GROUP BY students_vs_modules.module_id) AS ModuleAvgs
ON modules.module_id = ModuleAvgs.module_id
INNER JOIN YEAR ON modules.YEAR = YEAR.year_id
INNER JOIN exam_session ON students_vs_modules.academic_year = exam_session.academic_year
AND modules.semester = exam_session.semester
WHERE (student_records.user_id = @user_id)
ORDER BY modules.YEAR,
modules.semester,
modules.module_id;