1

我有三张桌子:

Student(StudentID, StudentName)
Course(CourseID, CourseName)
StudentCourse(StudentID, CourseID) -- junction table to assign courses to students

我将如何查询以获得最喜欢的课程 - “注册学生人数最多的课程”?

SQLFiddle

4

2 回答 2

6

尝试使用TOP...WITH TIES

SELECT  TOP 1 WITH TIES c.CourseName,
        COUNT(c.CourseID) totalCount
FROM    student a
        INNER JOIN studentcourse b
            ON a.studentID = b.studentID
        INNER JOIN course c
            ON b.courseID = c.courseID
GROUP BY c.CourseName
ORDER BY totalCount DESC

WITH TIES显示具有相同最高计数的记录。

SQLFiddle 演示

于 2012-10-15T07:37:12.267 回答
1
SELECT TOP 1 WITH TIES COURSEID 
FROM   STUDENTCOURSE 
GROUP  BY COURSEID 
ORDER  BY Count(*) DESC
于 2012-10-15T07:39:48.107 回答