查询数据以获得平均成绩

时间:2019-05-14 00:26:40

标签: sql postgresql

我正在尝试通过查询来自不同表的数据来获得平均成绩,尽管看起来一切都按预期进行,但该查询无法正常工作。表格如下:

grade(id_grade, id_subject, student_code and grade)
student(student_code, first_name, last_name, birthdate, average_grade)
subject(id_subject, credits, subject_code, name, teacher)

平均成绩的计算公式如下:(所有匹配成绩的总和(与学生中的学生代码相对应)*学生表中的平均成绩+学科的学分*最新增加的成绩)/(所有匹配成绩的总和+学分)。

查询如下:

UPDATE student AS s
SET 
    average_grade = ( 
        (SUM(g.grade) * s.average_grade + sub.credits * g.grade) / 
        (SUM(g.grade) + sub.credits) )
FROM grade AS g, subject AS sub
WHERE s.student_code = g.student_code AND 
    g.id_subject = sub.id_subject AND s.student_code = 141837;

请记住,这是PostgreSQL,因此某些输入可能与其他SQL-s不同,但这就是我能够想到的。 我也尝试了以下方法,但没有得到结果:

UPDATE student AS s 
LEFT JOIN grade AS g ON (s.student_code = g.student_code) 
LEFT JOIN subject AS sub ON (g.id_subject = sub.id_subject) 
SET average_grade = (
    (SUM(g.grade) * s.average_grade + sub.credits * g.grade) / 
    (SUM(g.grade) + sub.credits)) 
WHERE s.student_code = 141837;

我们非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您需要将其汇总为子查询。我认为平均计算不正确;我想您想要更多类似这样的东西:

UPDATE student s
    SET average_grade = g.average_grade
FROM (SELECT g.student_code,
             SUM(g.grade * s.credits) / SUM(s.credits) as average_grade
      FROM grade g JOIN
           subject s
           ON g.id_subject = s.id_subject
      GROUP BY g.student_code
     ) g
WHERE s.student_code = g.student_code AND
      s.student_code = 141837;