找到大多数课程的人

时间:2016-03-17 22:50:06

标签: sql-server tsql

我正在努力寻找参加大多数课程的人。我的结果应该是:

    Name     EnrolledCount
    David       4
    Mary        4

到目前为止,我提出了以下问题:

SELECT  S.Name,COUNT(*) AS EnrolledCount
FROM Student S
JOIN Student E ON S.id = E.id
GROUP BY S.Name

我从上述查询得到的结果是:

  Name  EnrolledCount
  David     4
  Jane      1
  John      2
  Mary      4
  Tom       2

请指点/建议。

2 个答案:

答案 0 :(得分:2)

如果您只想要注册最大数量的那些尝试使用这样的公用表表达式(还有其他解决方案。)

;with Enrolled (name, EnrolledCount) 
as 
(SELECT S.Name, COUNT(*) AS EnrolledCount 
FROM Student S
GROUP BY S.Name
)   
Select * from Enrolled 
where EnrolledCount = (select max(enrolledCount) from enrolled)
order by name  desc

答案 1 :(得分:1)

第二次编辑 - 使用排名功能对记录的数量按降序排列:

SELECT final.ID, final.Name, final.EnrollmentCount
  FROM (SELECT r.ID, 
               r.Name, 
               r.EnrollmentCount, 
               Ranking = RANK() OVER (PARTITION BY r.ID ORDER BY r.EnrollmentCount DESC)
          FROM (SELECT s.ID, 
                       s.Name, 
                       EnrollmentCount = COUNT(*)
                  FROM Student s
                 GROUP BY s.ID, s.Name) r) final
  WHERE final.Ranking = 1

上述内容首先确定了注册计数(最内层查询),然后是那些计数(内部查询)的排名,返回排名为1的结果过滤。

SELECT S.Name, S.EnrolledCount
  FROM Student S
 WHERE S.EnrolledCount = (SELECT MAX(i.EnrolledCount) FROM Student i)

编辑 - 我现在看到你的学生表上并没有实际注册了EnrolledCount,而是包含所有学生注册,因此学生出现的次数是该学生的计数。

SELECT S.ID, S.Name, EnrolledCount = COUNT(*)
  FROM Student S
 GROUP BY S.ID, S.Name
HAVING COUNT(*) = (SELECT TOP 1 COUNT(*) 
                     FROM Student i 
                    GROUP BY i.ID 
                    ORDER BY 1 DESC)