拥有表Student(列:StudentID,ClassID)。试着找出大多数学生的前三班。如果有相同数量的学生,也必须列出。一直在尝试以下方面:
SELECT
DISTINCT ClassID, COUNT(StudentID)
FROM
Student
GROUP BY ClassID
ORDER By COUNT(StudentID)
DESC Limit 3
但这并没有列出相同数量,事实上,如果有5个数字:40,20,20,10,5它将列出40,20,20。但我想列出前三名的结果40,20,20,10。
想知道是否有类似MySQL的排名可以用来解决这个问题。
答案 0 :(得分:3)
您可以加入前3个不同的计数值:
SELECT A.*
FROM (
SELECT COUNT(StudentID) AS student_count, ClassID
FROM Student
GROUP BY ClassID
) A INNER JOIN (
SELECT DISTINCT COUNT(StudentID) AS student_count
FROM Student
GROUP BY ClassID
ORDER BY student_count DESC
LIMIT 3
) B ON A.student_count = B.student_count
<强> THE SQL FIDDLE. 强>