带有SUM和MAX的MYSQL SELECT案例

时间:2019-06-10 12:24:28

标签: mysql select sum max case

在这个项目中,我试图创建一个查询,以根据大学生的成绩返回大学生的GPA总分。我正在使用MySQL 5.7.19,数据存储如下:

CourseID     Grade
5              A
8              D-
4              B-
8              B+
2              A

我使用CASE语句将字母等级转换为数字,并结合使用MAX函数和GROUP BY从不止一次的课程中获得更高的等级(在本例中为#8)...

SELECT MAX(
    CASE WHEN Grade = 'A+' OR Grade = 'A' THEN 4
        WHEN Grade = 'A-' THEN 3.67
        WHEN Grade = 'B+' THEN 3.33
        WHEN Grade = 'B'  THEN 3
        WHEN Grade = 'B-' THEN 2.67
        WHEN Grade = 'C+' THEN 2.33
        WHEN Grade = 'C'  THEN 2
        WHEN Grade = 'C-' THEN 1.67
        WHEN Grade = 'D+' THEN 1.33
        WHEN Grade = 'D'  THEN 1
        WHEN Grade = 'D-' THEN 0.67
        ELSE 0 END) AS Grade
FROM courses_taken WHERE Grade IS NOT NULL AND Grade != 'W'
GROUP BY CourseID

那很好,我得到以下结果:

Grade
4.00
2.67
3.33
4.00

但是我需要获取这些值的总和,当我尝试使用SUM函数时会出现错误:

SELECT SUM(MAX(
    CASE WHEN Grade = 'A+' OR Grade = 'A' THEN 4
        WHEN Grade = 'A-' THEN 3.67
        WHEN Grade = 'B+' THEN 3.33
        WHEN Grade = 'B'  THEN 3
        WHEN Grade = 'B-' THEN 2.67
        WHEN Grade = 'C+' THEN 2.33
        WHEN Grade = 'C'  THEN 2
        WHEN Grade = 'C-' THEN 1.67
        WHEN Grade = 'D+' THEN 1.33
        WHEN Grade = 'D'  THEN 1
        WHEN Grade = 'D-' THEN 0.67
        ELSE 0 END)) AS Total
FROM courses_taken WHERE Grade IS NOT NULL AND Grade != 'W'
GROUP BY CourseID

错误1111(HY000):组功能的无效使用

我尝试删除GROUP BY子句,但出现相同的错误。我也删除了MAX和GROUP BY,但是效果很好,但是我得到了所有成绩的总和,这不是我想要的。我想知道我到底在做什么错,或者是否还有其他方法可以做到这一点。

谢谢。

1 个答案:

答案 0 :(得分:1)

您不能在同一查询中堆叠多个聚合表达式。诀窍是对内部聚合使用子查询,然后对第二个聚合将其包装在另一个查询中。

SELECT SUM(Grade) Total
FROM (
SELECT MAX(
    CASE WHEN Grade = 'A+' OR Grade = 'A' THEN 4
        WHEN Grade = 'A-' THEN 3.67
        WHEN Grade = 'B+' THEN 3.33
        WHEN Grade = 'B'  THEN 3
        WHEN Grade = 'B-' THEN 2.67
        WHEN Grade = 'C+' THEN 2.33
        WHEN Grade = 'C'  THEN 2
        WHEN Grade = 'C-' THEN 1.67
        WHEN Grade = 'D+' THEN 1.33
        WHEN Grade = 'D'  THEN 1
        WHEN Grade = 'D-' THEN 0.67
        ELSE 0 END) AS Grade
FROM courses_taken WHERE Grade IS NOT NULL AND Grade != 'W'
GROUP BY CourseID) max_grade