Question

I would like to write a SQL query that would list all teachers that have more than three (3) students in their class (Mrs. Smith in this case). I originally thought that the HAVING clause would be the correct way to accomplish this but I am not coming up with Mrs. Smith as expected.

Teacher         Student
-------------------------
Mrs. Smith      Danny
Mrs. Smith      Emily
Mrs. Smith      Todd
Mrs. Smith      Paul
Mr. French      Sam
Mr. French      Carol
Mr. French      Patty

SELECT DISTINCT Teacher
FROM Students 
HAVING (COUNT(Teacher) > 3)
GROUP BY Teacher, Student
Was it helpful?

Solution

Using HAVING is correct, you just need to use it correctly

SELECT Teacher
FROM Students 
GROUP BY Teacher
HAVING COUNT(Student) > 3

Basically you're grouping Teacher records together while counting how many Students each teacher has. And filtering on that count.

OTHER TIPS

Yes, HAVING is correct. Try:

SELECT Teacher
FROM Students 
GROUP BY Teacher
HAVING (COUNT(1) > 3)

I think you just need to place your HAVING clause at the end:

SELECT DISTINCT Teacher
FROM Students 
GROUP BY Teacher, Student
HAVING COUNT(Teacher) > 3;

all teachers that have more than three students

So:

select teacher, count(student) --All Teachers
FROM Students 
GROUP BY Teacher
HAVING COUNT(student) > 3  --Having more than three students

Change it to only group by Teacher and put Having after Group By

SELECT Teacher
FROM Students    
GROUP BY Teacher
HAVING (COUNT(Teacher) > 3)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top