更新 我有这样的查询
select sl.College_ID,sl.Department_ID,COUNT(sl.RegisterNumber) from StudentList sl
group by sl.College_ID,sl.Department_ID
order by sl.College_ID,sl.Department_ID asc
abouve query提供以下结果 我有200个大学学历,每个大学有6个部门_我可以得到每个部门的[学生数]
College_Id Dept_Id count
1 1 100
1 2 210
2 3 120
2 6 80
3 1 340
但我的问题是我需要显示每个部门的最大人数[学生]
像这样的事情
college_ID Dept_Id count
3 1 340
26 2 250
我尝试了这个,但得到了错误
select sl.College_ID,sl.Department_ID,COUNT(sl.RegisterNumber) from StudentList sl
group by sl.College_ID,sl.Department_ID
having COUNT(sl.RegisterNumber)=max(COUNT(sl.RegisterNumber))
order by sl.College_ID,sl.Department_ID asc
出了什么问题,有人可以帮助我
答案 0 :(得分:2)
也许是这样的?
SELECT sl.College_ID, sl.Department_ID, COUNT(sl.RegisterNumber) As StudentCount, s2.MaxCount
FROM StudentList sl
INNER JOIN (
SELECT Department_ID, MAX(StudentCount) AS MaxCount
FROM (
SELECT College_ID, Department_ID, COUNT(*) As StudentCount
FROM StudentList
GROUP BY College_ID, Department_ID
) s1
GROUP BY Department_ID
) s2 ON sl.Department_ID = s2.Department_ID
GROUP BY sl.College_ID, sl.Department_ID, s2.MaxCount
HAVING COUNT(sl.RegisterNumber) = s2.MaxCount
ORDER BY sl.College_ID, sl.Department_ID ASC
编辑:我已更新查询以更准确地回答您的问题,我错过了您希望College_ID
获得最大数量的部分。
编辑2 :好的,这个现在应该工作,我需要第二个嵌套子查询来聚合聚合。我不知道比较不同群体的聚合的更好方法。
答案 1 :(得分:0)
您想要的结果,即 college_ID 上的群组,您并不真正关心 college_ID ,因为从您的示例来看,Dept_Id = 1将无法确定哪个college_ID是
在这种情况下,您可以从select语句中删除 college_ID 并执行SUM
GROUP BY
基于您的查询,例如:
SELECT t.Department_ID, SUM(t.c)
FROM (
select sl.College_ID,sl.Department_ID,COUNT(sl.RegisterNumber) c from StudentList sl
group by sl.College_ID,sl.Department_ID
) t
GROUP BY t.Department_ID
ORDER BY SUM(t.c)
注意:如果您的结果中确实需要 college_ID ,则可以JOIN
获取 college_ID