SQL(两个表)查询最受欢迎的课程

时间:2017-10-06 11:17:04

标签: sql tsql

我无法返回最常见的课程 问题是:编写一个Query来返回最常见课程的CourseName

StudentCourses:
     StudentCourseID
     StudentID
     CourseID

Courses:
     CourseID
     CourseName

我有这个

SELECT CourseName
From Courses c
WHERE CourseID = (SELECT Count(CourseID) AS Course_Value
                FROM StudentCourses
                Group BY CourseID
                Order BY Course_Value DESC
                LIMIT 1;

我知道这不对,但我是否正确使用COUNT来正确找到最受欢迎的课程?

2 个答案:

答案 0 :(得分:4)

SELECT Top 1 CourseName 
FROM   Courses
JOIN   StudentCourses
  ON   Courses.CourseId = StudentCourses.CourseId
GROUP BY CourseName
ORDER BY Count(CourseName) DESC

答案 1 :(得分:3)

对于此类问题,请学会使用明确的git pulljoin

top

如果您想要联系,请使用select top (1) c.courseid, c.coursename, count(*) as cnt from studentcourses sc join courses c on sc.courseid = c.courseid group by c.courseid, c.coursename order by count(*) desc;