我有三张桌子:
Student(StudentID, StudentName)
Course(CourseID, CourseName)
StudentCourse(StudentID, CourseID) -- junction table to assign courses to students
我将如何查询以获得最喜欢的课程 - “注册学生人数最多的课程”?
尝试使用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
显示具有相同最高计数的记录。
SELECT TOP 1 WITH TIES COURSEID
FROM STUDENTCOURSE
GROUP BY COURSEID
ORDER BY Count(*) DESC