Reputation: 2128
I'm trying to write a SQL statement to find all of the rows in a table that, for one field, contain the same values. However I only want to return the rows that have different values for a separate attribute. This is a little hard to explain.
I have a table Teacher with the schema:
TeacherName varchar(50)
CourseN int
Quarter varchar(50)
The three fields combined make up the primary key, so the same teacher can teach the same course so long as the quarter is different. The problem I'm trying to solve is, how can I return the (distinct) names of all the teachers who teach at least two different courses (regardless of quarter)?
This is for a lab and I've been trying to solve this problem for about a week and I just cannot figure it out, so I figured I would come here. The previous question asked to find the distinct list of names of teachers who teach the same course at least twice. I came up with this:
SELECT DISTINCT [TeacherName]
FROM [Teacher]
GROUP BY [TeacherName],
[CourseN]
HAVING COUNT( [CourseN] ) >= 2
However the problem I'm trying to solve now is similar, but again, I need only teachers who show up in the table more than once that teach at least two different courses. I would really appreciate some guidance as well, rather than just the answer, since it's important that I understand exactly what the database is doing.
Upvotes: 2
Views: 6161
Reputation: 1850
You should be able to get the distinct list without having to use the word DISTINCT in this case, particularly if it can be "regardless of quarter". Essentially, you just want the teachers who have >=2 rows in the subquery table that has 1 row per unique teacher-coursenumber combination.
select TeacherName
from (
select TeacherName, CourseN
from Teacher
group by TeacherName, CourseN
) t1
group by TeacherName
having count(*) >=2
Upvotes: 3