开发者

SQL Count occurrence of a value

I'm working a course creation application, where the user needs to display all the students in X number of courses. For example, if a biology class is selected, the user should be able to filter users based on how many other courses they are already in. My table has the following fields: id, uid, courseid. I want to do something like but don't know what the syntax should be:

SELECT * FROM course_list WHERE count(uid) > X AND courseid=Z

Where X is the number of courses the user has filtered to (a value 0-3), and Z is simply the开发者_如何学Python id of the course the user is currently looking at.


You can't use aggregate functions in the where clause of a query. Instead, they belong in the having portion of the query so you would need something like:

select StudentId
from course_list
where CourseId = @CourseId
group by StudentId
having count(uid) > @MaxCount

...or something to that effect.


Alternatively, you could structure your database thusly:

Table: Students (includes an autoincrementing ID field StudentId)
Table: Cources (includes an autoincrementing ID field CourseId)
Table: StudentCourseAssociation (Includes studentId, courseId, and quarter/semester/year/whatever information)

Then you just:

SELECT StudentId, Count(*) FROM StudentCourseAssociation
WHERE StudentId IN 
(
    SELECT StudentId FROM StudentCourseAssociation WHERE CourseId = @CourseId
)
AND NOT CourseId = @CourseId
GROUP BY StudentId

That should get all students in the course, and give you their ID and the count of other classes they have. My syntax may be incorrect, as I'm typing this from memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜