MYSQL计算结果

时间:2011-05-17 18:28:00

标签: mysql sum

我正在mysql 5.0中构建一个查询来计算学生学期成绩。初始表(studentItemGrades)包含将用于计算最终成绩的作业列表等。每项作业都有一个PossibleScore,Grade和Weight。计算应对所有类似加权的项目进行分组,并根据分配到期的日期范围提供SUM(GRADE)/ SUM(POSSIBLESCORE)。我遇到的问题是所有个别加权等级的最终总和。例如,结果目前产生以下结果:

CourseScheduleID    sDBID   AssignedDate    DueDate     Weight  WeightedGrade
1           519     2010-08-26  2010-08-30  10  0.0783333333333333
1           519     2010-09-01  2010-09-03  20  0.176
1           519     2010-09-01  2010-09-10  70  0.574
来自查询的

SELECT CourseScheduleID, sDBID, AssignedDate, DueDate, Weight, 
((SUM(Grade)/SUM(PossibleScore))*(Weight/100)) AS WeightedGrade 
FROM studentItemGrades 
WHERE DueDate>='2010-08-23' 
AND DueDate<='2010-09-10' 
AND CourseScheduleID=1 
AND sDBID=519 
AND Status>0 
GROUP BY Weight

问题:我如何在WeighedGrade输出中对三个结果进行求和?顺便说一句,这是计算特定校园所有课程所有成绩的更大查询的一部分。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:9)

您可以使用子查询,如下所示:

SELECT SUM(WeightedGrade) FROM
(
  SELECT CourseScheduleID, sDBID, AssignedDate, DueDate, Weight, 
    ((SUM(Grade)/SUM(PossibleScore))*(Weight/100)) AS WeightedGrade 
  FROM studentItemGrades 
  WHERE DueDate>='2010-08-23' 
  AND DueDate<='2010-09-10' 
  AND CourseScheduleID=1 
  AND sDBID=519 
  AND Status>0 
  GROUP BY Weight
) t1

答案 1 :(得分:1)

为了对三个结果求和,您需要使用另一个具有group by的select来重新查询此select的结果。这可以通过使用子查询使用单个sql语句来完成。

SELECT sq.CourseScheduleID, sq.sDBID, SUM(sq.WeightedGrade) as FinalGrade
FROM
(
  SELECT CourseScheduleID, sDBID, AssignedDate, DueDate, Weight, 
         ((SUM(Grade)/SUM (PossibleScore))*(Weight/100)) AS WeightedGrade 
    FROM studentItemGrades WHERE DueDate>='2010-08-23' AND DueDate<='2010-09-10' 
         AND CourseScheduleID=1 AND sDBID=519 AND Status>0 GROUP BY Weight
) AS sq
GROUP BY sq.CourseScheduleID, sq.sDBID