Reputation: 576
I am currently studying for a final, and one of the study questions from a previous exam is as follows:
You have the following schema:
Student( Snum
: integer, Sname
: string, Major
: string, Class
: string, Age
: string)
Course( Cname
: string, Meets_at
: time, Room
: string, Fid
: Integer)
Faculty( Fid
: Integer, Fname
: string, Deptid
: integer)
Enrolled( Snum
: integer, Cname
: integer)
The question I am having problems with is:
"Find the names of all faculty members who teach in every room that some class meets"
Here is what I have so far:
SELECT DISTINCT( Fname )
FROM (FACULTY NATURAL JOIN COURSE AS C1), COURSE AS C2
WHERE C1.Room = C2.Room
GROUP BY Fname,C2.Cname
WHERE COUNT(C1.Room) = (SELECT COUNT(DISTINCT(Room))
FROM COURSE
WHERE Cname = C2.Cname);
I think I'm on the right track, but I'm not sure if this is right. Any help would be appreciated!
Upvotes: 0
Views: 288
Reputation: 88
yes I think you are on the right track with the strategy of matching the count per faculty member to the count of distinct rooms on the course table.
try the following query:
SELECT DISTINCT F.Fname
FROM
Faculty AS F
INNER JOIN
(SELECT Fid, COUNT(DISTINCT Room) AS cnt FROM Course
GROUP BY Fid
) rooms_per_faculty
ON F.Fid = rooms_per_faculty.Fid
INNER JOIN
(SELECT COUNT(DISTINCT Room) AS cnt FROM Course) rooms_that_meet
ON rooms_per_faculty.cnt = rooms_that_meet.cnt
(might help to have a little data to play around with. in the below example, only Dr.4 meets the criteria - teaching in all three course rooms - A,B,C)
create local temporary table course(Room varchar(1), Fid int);
create local temporary table faculty(Fid int, Fname varchar(3));
insert into faculty
select 1, 'DR1'
union select 2, 'DR2'
union select 3, 'DR3'
union select 4, 'DR4';
insert into course
select 'A',1
union select 'B',1
union select 'A',2
union select 'C',3
union select 'B',4
union select 'A',4
union select 'C',4;
Upvotes: 1