【问题标题】:How to Average only those that have a sum greater than in SQL query如何仅对总和大于 SQL 查询的那些进行平均
【发布时间】:2019-04-12 16:20:29
【问题描述】:

如何仅获取 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 个或更多学分的学生。

【问题讨论】:

  • 能否请您添加表结构、示例数据和您想要的结果?

标签: sql-server average


【解决方案1】:

首先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 

【讨论】:

    【解决方案2】:

    我会用一个内表来做这个:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多