我想知道我该怎么做:
我有三张桌子:
Student(StudentID, StudentName)
Course(CourseID, CourseName)
StudentCourse(StudentID, CourseID) -- junction table to assign courses to students
如何根据条件查询获取最喜欢的课程 “登记的学生人数最多的课程是 最喜欢的课程“
帮助??
我已经在sql fiddle设置了架构
答案 0 :(得分: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
显示具有相同最高计数的记录。
答案 1 :(得分:1)
SELECT TOP 1 WITH TIES COURSEID
FROM STUDENTCOURSE
GROUP BY COURSEID
ORDER BY Count(*) DESC