0

使用 mySQL...

我试图返回仅包含 id、name 和 GPA 的不同元组,其中 gpa 遵循这个新公式:

GPA =总和(数学成绩*学分)/总和(学分)

(所以我要返回每个课程的成绩,包括学分,这样我就有了计算上述公式所需的信息。我只想返回 ID、姓名和 GPA,让 GPA 使用上面的公式。)

Zhang 的 IE 看​​起来像:

for each tuple where ID = 00128
{ GPA = GPA * credits / totalCreditsForThisStudent; }

我已经做到了这一点:

这是我的 SQL 语句和结果:

SELECT id, name, (
CASE 
WHEN grade LIKE 'A' 
then 4.0
WHEN grade LIKE 'A-' 
then 3.67
WHEN grade LIKE 'B+' 
then 3.33
WHEN grade LIKE 'B' 
then 3
WHEN grade LIKE 'B-' 
then 2.67
WHEN grade LIKE 'C+' 
then 2.33
WHEN grade LIKE 'C' 
then 2
WHEN grade LIKE 'C-' 
then 1.67
WHEN grade LIKE 'D+' 
then 1.33
WHEN grade LIKE 'D' 
then 1
WHEN grade LIKE 'D-' 
then 0.67
WHEN grade LIKE 'F' 
then 0
END) as GPA, credits 
FROM student natural join takes natural join course
WHERE grade is not null
;


Output:
id      name    GPA     credits
00128   Zhang   4.00    4
00128   Zhang   3.67    3
12345   Shankar 2.00    4
12345   Shankar 4.00    4
12345   Shankar 4.00    3
12345   Shankar 4.00    3
19991   Brandt  3.00    3
23121   Chavez  2.33    3
44553   Peltier 2.67    4
etc...
4

1 回答 1

1

看起来您不像聚合那样需要不同的记录:

SELECT 
    id
    , name
    , SUM(
            (
                CASE 
                    WHEN grade LIKE 'A' 
                        then 4.0
                    WHEN grade LIKE 'A-' 
                        then 3.67
                    WHEN grade LIKE 'B+' 
                        then 3.33
                    WHEN grade LIKE 'B' 
                        then 3
                    WHEN grade LIKE 'B-' 
                        then 2.67
                    WHEN grade LIKE 'C+' 
                        then 2.33
                    WHEN grade LIKE 'C' 
                        then 2
                    WHEN grade LIKE 'C-' 
                        then 1.67
                    WHEN grade LIKE 'D+' 
                        then 1.33
                    WHEN grade LIKE 'D' 
                        then 1
                    WHEN grade LIKE 'D-' 
                        then 0.67
                    WHEN grade LIKE 'F' 
                        then 0
                END
            ) 
        ) / 
        SUM(credits)
        as GPA
FROM 
    student 
natural join 
    takes 
natural join 
    course
WHERE grade is not null
GROUP BY 
    id
    , name
;
于 2013-05-28T18:17:15.847 回答