如何仅对SQL查询中的学分总和大于或等于15个学分的那些学生获得学分总和的平均值?
使用HAVING(SUM(STC_ATT_CRED))> = 15.0时,它为我提供了所有学生的平均数,而不仅仅是具有15.0或更高总学分的学生。
SELECT (SUM(STC_ATT_CRED) )/COUNT(DISTINCT stc_person_id) as 'average attempted credit',
COUNT (DISTINCT stc_person_id)
FROM dbo.S85_STUDENT_ACAD_CRED
WHERE (STC_TERM='2018FA') AND ((STC_VERIFIED_GRADE IS NOT NULL ))
AND STC_PERSON_ID IN (75 student id's in here)
HAVING (SUM(stc_att_cred)) >= 15.0
我希望输出为仅符合条件的46名学生的尝试学分总数的平均值(尝试学分总数15或更多)。
取而代之的是,输出结果使我平均获得了全部75名学生,而没有将其范围缩小到只有15个或更多学分的学生。
答案 0 :(得分:0)
首先GROUP BY stc_person_id
得到每个学生的总和,然后以所有学生的stc_att_cred >= 15.0
的总和为条件来过滤结果,并得到平均值:
SELECT
SUM(t.studentsum) / COUNT(*) 'average attempted credit',
count(*)
FROM (
SELECT
stc_person_id,
SUM(STC_ATT_CRED) studentsum
FROM dbo.S85_STUDENT_ACAD_CRED
WHERE
STC_TERM='2018FA'
AND
STC_VERIFIED_GRADE IS NOT NULL
AND
STC_PERSON_ID IN (75 student id's in here)
GROUP BY stc_person_id
) t
WHERE t.studentsum >= 15.0
答案 1 :(得分:0)
我会用一个内部表来做到这一点:
SELECT avg here
FROM
(
--Get the students and sum credits
--Filter this list for students with sum >= 15
SELECT STC_PERSON_ID, SUM(stc_att_cred) as studentSum
FROM dbo.S85_STUDENT_ACAD_CRED
WHERE (STC_TERM='2018FA') AND ((STC_VERIFIED_GRADE IS NOT NULL )) AND
STC_PERSON_ID IN (75 student id's in here)
GROUP BY STC_PERSON_ID
HAVING (SUM(stc_att_cred)) >= 15.0
)studentsWithSumCreditsOverFifteen