我有一个表学生,其中包含以下列:
id subject grade date
---|-------|------|-----------|
1 | A | 1 | 01-MAR-10 |
1 | A | 5 | 05-APR-10 |
1 | B | 3 | 01-JUN-10 |
2 | A | 1 | 01-MAR-10 |
2 | C | 3 | 01-APR-10 |
在我的程序中,我传递了学生ID(p_id),我需要为该学生选择所有科目的平均成绩,如果学生对同一科目有2个成绩,只有最新成绩,如下:
表示p_id = 1:
id avgGrade
---|--------|
1 | 4 |
这是现在完成的
我现在需要做什么,在字符串中保存学生成功的信息并用DBMS_OUTPUT打印。最高等级是1,最低等级是5.如果一个学生只有一个5(作为一个主题的最后一个等级),无论他有什么平均数,该字符串应该包含“学生失败”,如果学生没有5作为最后一个成绩,并且平均值<= 1,5,字符串应包含“完美平均值”,否则只是“学生通过”
到目前为止的代码是:
CREATE OR REPLACE Procedure avg_grade
( p_id IN number )
IS
cursor c1 is
select a.id, avg(a.grade) avg_grade
from student a
inner join
(
select id, subject, max(date) max_date
from student
where id=p_id
group by id, subject
)b ON a.id=b.id and
a.subject=b.subject and
a.date=b.max_date
where a.id=p_id
group by id;
cursor c2 is
select grade
from student
where id=p_id;
DECLARE @out as varchar(50)
SET @out=NULL
IF c2.grade IN(5)
BEGIN
SET @out='student failed'
END
ELSE IF c2.grade NOT IN(5) AND c1.avg_grade IN (BETWEEN 1 AND 1,5)
BEGIN
SET @out='student has a perfect average'
END
ELSE
BEGIN
SET @out='student passed'
END
DBMS_OUTPUT.PUT_LINE(@out);
请帮助
答案 0 :(得分:1)
SELECT a.ID, AVG(a.grade) AVG_GRADE
FROM TableName a
INNER JOIN
(
SELECT ID, Subject, MAX(date) max_date
FROM TableName
WHERE ID = 1 -- <<== change it to p_id
GROUP BY ID, Subject
) b ON a.ID = b.ID AND
a.Subject = b.Subject AND
a.date = b.max_date
WHERE a.ID = 1 -- <<== change it to p_id
GROUP BY a.ID