2012-11-28 114 views
1

嗨,我是Oracle SQL新手,我想編寫一個SQL語句,可以從表中讀取成績併爲學生生成gpa。下面是我寫的一個示例代碼和它不工作:oracle 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 
.... 
.... 
.... 
.... 

任何人都可以請幫助????

回答

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 
+0

非常感謝,它工作正常。再次感謝 –

+0

@AvineshKumar - 不客氣。 –