0

我正在尝试列出在第 3 次测验中成绩低于平均水平的学生。

首先我选择

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;

我做错了什么,如何列出成绩低于平均水平的学生?

4

1 回答 1

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)
于 2013-10-18T04:41:23.503 回答