문제

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
도움이 되었습니까?

해결책

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.

다른 팁

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top