2013-10-18 68 views
0

我想列出在第三次測驗中收到低於平均成績的學生。低於AVG子查詢不顯示正確的結果

首先我選擇

SELECT s.STUDENT_ID, s.LAST_NAME,g.GRADE_TYPE_CODE,AVG (g.NUMERIC_GRADE) AS GRADE 
FROM STUDENT s, GRADE g 
WHERE s.STUDENT_ID = g.STUDENT_ID 
AND g.SECTION_ID = 135 AND g.GRADE_TYPE_CODE= 'QZ' AND g.GRADE_CODE_OCCURRENCE = 3 
GROUP BY s.STUDENT_ID, s.LAST_NAME,g.GRADE_TYPE_CODE 

和我收到的平均四個結果

STUDENT_ID LAST_NAME      GRADE 
---------- ------------------------- ---------- 
    178  Kurtz        98 
    215  Chatman       90 
    259  Merriman       81 
    214  Williams       99 

但是當我要選擇那些誰接受低於平均水平,我得到165行中選擇

SELECT z.STUDENT_ID, z.LAST_NAME 
    FROM STUDENT z, GRADE w 
    WHERE z.STUDENT_ID = w.STUDENT_ID 
    GROUP BY z.STUDENT_ID, z.LAST_NAME 
    HAVING COUNT(*) < 
    (SELECT AVG(GRADE) 
    FROM 
    (SELECT s.STUDENT_ID, s.LAST_NAME,g.GRADE_TYPE_CODE,AVG (g.NUMERIC_GRADE) AS GRADE 
    FROM STUDENT s, GRADE g 
    WHERE s.STUDENT_ID = g.STUDENT_ID 
    AND g.SECTION_ID = 135 AND g.GRADE_TYPE_CODE= 'QZ' AND g.GRADE_CODE_OCCURRENCE = 3 
    GROUP BY s.STUDENT_ID, s.LAST_NAME,g.GRADE_TYPE_CODE)) 

ORDER BY z.LAST_NAME; 

我在做什麼錯,我如何列出收到低於平均成績的學生?

回答

3

如果我正確理解你的問題,下面是一個使用common table expression的簡化版本,採用avg() over()

with cte as (
    select s.student_id, s.last_name, g.numeric_grade, 
    avg(g.numeric_grade) over() average 
    from student s 
    join grade g on s.student_id = g.student_id 
    where g.section_id = 135 
    and g.grade_type_code = 'QZ' 
    and g.grade_code_occurence = 3 
) 
select student_id, last_name 
from cte 
group by student_id, last_name 
having avg(numeric_grade) < avg(average)