我想获得一份在期末考试中取得高于平均水平的学生名单
我首先选择获得平均值
SELECT w.LAST_NAME , AVG(s.NUMERIC_GRADE) AS NUMERIC_GRADE
GRADE s , SECTION z, STUDENT w
WHERE s.SECTION_ID = z.SECTION_ID AND s.STUDENT_ID = w.STUDENT_ID
AND s.SECTION_ID = 90 AND s.GRADE_TYPE_CODE = 'FI'
GROUP BY w.LAST_NAME,s.NUMERIC_GRADE
我得到了这四个结果
LAST_NAME NUMERIC_GRADE
------------------------- -------------
Mulroy 83
Da Silva 92
Lopez 91
Abid 84
但是当我尝试从这四个中得到上述平均值时,我没有得到任何行,看起来子查询和主查询具有相同的条件。我不确定在avg之后如何做。
SELECT n.LAST_NAME , m.NUMERIC_GRADE
FROM GRADE m , STUDENT n
WHERE m.STUDENT_ID = n.STUDENT_ID
GROUP BY n.LAST_NAME , m.NUMERIC_GRADE
HAVING COUNT(*) >
(SELECT AVG (NUMERIC_GRADE)
FROM
(SELECT w.LAST_NAME , AVG(s.NUMERIC_GRADE) AS NUMERIC_GRADE
FROM GRADE s , SECTION z, STUDENT w
WHERE s.SECTION_ID = z.SECTION_ID AND s.STUDENT_ID = w.STUDENT_ID
AND s.SECTION_ID = 90 AND s.GRADE_TYPE_CODE = 'FI'
GROUP BY w.LAST_NAME,s.NUMERIC_GRADE))
ORDER BY n.LAST_NAME;
我想获得numberic_grade 91和92,因为它高于平均水平。当我试图选择那些在期末考试中具有高于平均水平的人时,为什么它没有给我任何行?
答案 0 :(得分:1)
您的查询存在以下问题:
AVG
查询中使用GROUP BY
GRADE
表尝试使用这些更正的查询:
SELECT n.LAST_NAME , AVG(m.NUMERIC_GRADE)
FROM GRADE g
JOIN STUDENT s ON g.STUDENT_ID = s.STUDENT_ID -- Use ANSI joins
WHERE g.SECTION_ID = 90 AND g.GRADE_TYPE_CODE = 'FI'
GROUP BY s.LAST_NAME
HAVING AVG(g.NUMERIC_GRADE) >
(SELECT AVG(NUMERIC_GRADE)
FROM (
SELECT AVG(g.NUMERIC_GRADE) AS NUMERIC_GRADE
FROM GRADE g
JOIN STUDENT s ON s.STUDENT_ID = g.STUDENT_ID
WHERE g.SECTION_ID = 90 AND g.GRADE_TYPE_CODE = 'FI'
GROUP BY s.LAST_NAME
)
)
ORDER BY s.LAST_NAME;