获得子计数以及平均值和计数

时间:2015-03-19 08:57:27

标签: sql sql-server count average

我有两张桌子......

MODULES                ENROLMENTS
GroupNo                StudentNo
Title                  GroupNo
Tutor                  CourseworkMark
DayNo                  ExamMark
Time
Room
Semester

我希望创建一个视图,显示每个模块的课程作业和考试中取得的平均分数,以及达到> 70,60-69,50-59,40-49和&lt的学生数量的计数; 40。这可能吗?

我的平均分数是......

SELECT Title,
       AVG(CourseworkMark) AS AverageCoursework,
       AVG(ExamMark) AS AverageExam
FROM tblModules INNER JOIN tblEnrolments
   ON tblModules.GroupNo = tblEnrolments.GroupNo
GROUP BY Title;

1 个答案:

答案 0 :(得分:1)

您可以使用SUMmed CASE表达式执行此操作;

SELECT Title,
       AVG(CourseworkMark) AS AverageCoursework,
       AVG(ExamMark) AS AverageExam,
       SUM(CASE WHEN CourseworkMark > 70 THEN 1 ELSE 0 END) AS CourseworkMarkOver70,
       SUM(CASE WHEN CourseworkMark BETWEEN 60 AND 70 THEN 1 ELSE 0 END) AS CourseworkMarkOver60To69,
       SUM(CASE WHEN CourseworkMark BETWEEN 50 and 59 THEN 1 ELSE 0 END) AS CourseworkMarkOver50To59,
       SUM(CASE WHEN CourseworkMark BETWEEN 40 and 49 THEN 1 ELSE 0 END) AS CourseworkMarkOver40To49,
       SUM(CASE WHEN CourseworkMark < 40 THEN 1 ELSE 0 END) AS CourseworkMarkUnder40
FROM tblModules INNER JOIN tblEnrolments
   ON tblModules.GroupNo = tblEnrolments.GroupNo
GROUP BY Title;