嵌套查询中的SQL Server查询更正

时间:2012-12-26 10:27:41

标签: sql sql-server select

SELECT campus,semester, AVG(CountOfStudents)
FROM
(
  SELECT semester,year,campus, count(*) as CountOfStudents
  FROM regestration
  GROUP BY  semester, year, campus,student_id
) t
GROUP BY   campus,semester

我需要做的是找到每个校区每个学期的平均人数

我的表结构是:

表名 - 注册

student_id
campus
year
batch
semester

campusyearsemesterbatch这些可以帮助识别唯一记录,而student_id可能会重复,上面的查询会给出错误答案。

1 个答案:

答案 0 :(得分:1)

请按照以下步骤操作:

  • student_ID子句和
  • 中删除GROUP BY
  • DISTINCT
  • 中添加COUNT()

查询,

SELECT campus, semester, AVG(CountOfStudents)
FROM
(
  SELECT semester, year, campus, count(DISTINCT student_id) as CountOfStudents
  FROM   registration
  GROUP BY  semester, year, campus
) t
GROUP BY   campus, semester