oracle sql从成绩中计算gpa

时间:2012-11-28 07:49:38

标签: database oracle plsql

您好我是Oracle SQL新手,我想编写一个SQL语句,可以从表中读取成绩并为学生生成gpa。下面是我编写的示例代码,它不起作用:

select id,
declare gpa = 0;
BEGIN
    IF grade = 'A+' THEN gpa = gpa + 4.5;
    ELSIF grade = 'A' THEN gpa = gpa + 4;
    ELSIF grade = 'B+' THEN gpa = gpa + 3.5;
    ELSIF grade = 'B' THEN gpa = gpa + 3;
    ELSIF grade = 'C+' THEN gpa = gpa + 2.5;
    ELSIF grade = 'C' THEN gpa = gpa + 2;
    ELSE gpa = gpa + 0;
    END IF
    gpa = gpa/count(grade)
END
gpa from table where id in ('s11','s12','s13','s14')
group by id

表格中的数据示例如下:

id                   grade
--------------------------
s11                  A
s11                  B+
s11                  A+
s11                  C
s12                  C+
s12                  A
s12                  D
s12                  B
s13                  A+
s13                  C+
s13                  B
s13                  A
s13                  A
....
....
....
....

任何人都可以帮忙????

1 个答案:

答案 0 :(得分:3)

尝试这样的事情:

select id, sum(case name 
                    when 'A+' then 4.5 
                    when 'A' then 4
                    when 'B+' then 3.5
                    when 'B' then 3
                    when 'C+' then 2.5
                    when 'C' then 2
                    else 0
               end
               )/count(*) gpa
from table 
where id in ('s11','s12','s13','s14')
group by id