I want to do something like the following:
SELECT studentName, COUNT(lessonCode)
FROM Lessons
WHERE
COUNT(lessonCode) = 10
Currently, I’m getting all the students in the lessons table, along with the number of lessons they have, and saving the information in a table variable called studentInfo.
DECLARE @studentInfo TABLE
(
studentName varchar,
numLessons int
)
INSERT INTO @studentInfo (studentName, numLessons)
SELECT studentName, COUNT(lessonCode)
FROM Lessons
Then I’m using that in another select statement:
select studentName
FROM @studentInfo
WHERE
numLessons = 10
This works fine, but the only problem is that there are about 30,000 students in my database, so the query where I get the list of students and the number of lessons they have is taking a very long time, and generally doesn’t finish before I cancel the execution of the query, usually at around 30 minutes. Is there any other way to do this more efficiently, and to achieve what I’m looking for at the top of this post?
Thanks.
Use the
HAVINGclause:Also, consider creating an index on
Lessons(studentName, lessonCode), it will speed your query, since you’ll be able to process it only by accessing the index.