简体   繁体   中英

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM