学生课程表查询中的收藏课程

时间:2012-10-15 07:32:23

标签: sql join

我想知道我该怎么做:

我有三张桌子:

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

如何根据条件查询获取最喜欢的课程   “登记的学生人数最多的课程是   最喜欢的课程“

帮助??

我已经在sql fiddle设置了架构

SQLFiddle

2 个答案:

答案 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显示具有相同最高计数的记录。

SQLFiddle Demo

答案 1 :(得分:1)

SELECT TOP 1 WITH TIES COURSEID 
FROM   STUDENTCOURSE 
GROUP  BY COURSEID 
ORDER  BY Count(*) DESC