To avoid the magic number 99:
SELECT
P.pid
FROM
(
SELECT DISTINCT
Pi.pid, M.Director
FROM Production Pi
JOIN Movie M ON Pi.mid = M.mid
) P
GROUP BY
P.pid
HAVING
COUNT(p.Director) = 2 -- The directors should be exactly 2
AND MIN(CASE WHEN p.Director in ('Ben Affleck', 'Peter Jackson')
THEN 1 ELSE 0 END) = 1
Other approaches: http://www.anicehumble.com/2019/04/not-every-rdbms-has-every.html
Note that the double not in
approach can't be used. As it will still report the publishers that has one director only that matches Ben Affleck or Peter Jackson.
with production as
(
select *
from (values
('DC', 'Batman', 'Ben Affleck'),
('DC', 'Robin', 'Peter Jackson'),
('Not DC', 'Not Batman', 'Not Ben Affleck'),
('Not DC', 'Not Robin', 'Not Peter Jackson'),
('Marvel', 'Avengers', 'Joe Russo'),
('WingNut', 'King Kong', 'Peter Jackson'),
('Century Fox', 'Deadpool', 'Ben Affleck'),
('Century Fox', 'Fantastic 4', 'Peter Jackson'),
('Century Fox', 'X-Men', 'Peter Jackson'),
('Millenium Fox', 'Scorpion', 'Ben Affleck'),
('Millenium Fox', 'Sub-Zero', 'Peter Jackson'),
('Millenium Fox', 'Liu Kang', 'Ed Boon')
) as x(publisher, movie, director)
)
select distinct P.publisher
from production P
where P.publisher not in (
-- Get publishers that have produced a movie directed by someone else
select P1.publisher
from production P1
where P1.director not in ('Ben Affleck', 'Peter Jackson')
)
;
Wrong output. WingNut should not be included, as it don't have both Ben Affleck and Peter Jackson as directors.
| publisher |
| ----------- |
| WingNut |
| Century Fox |
| DC |
Here's the correct query, every is simulated using min(when true then 1 else 0) = 1
with production as
(
select *
from (values
('DC', 'Batman', 'Ben Affleck'),
('DC', 'Robin', 'Peter Jackson'),
('Not DC', 'Not Batman', 'Not Ben Affleck'),
('Not DC', 'Not Robin', 'Not Peter Jackson'),
('Marvel', 'Avengers', 'Joe Russo'),
('WingNut', 'King Kong', 'Peter Jackson'),
('Century Fox', 'Deadpool', 'Ben Affleck'),
('Century Fox', 'Fantastic 4', 'Peter Jackson'),
('Century Fox', 'X-Men', 'Peter Jackson'),
('Millenium Fox', 'Scorpion', 'Ben Affleck'),
('Millenium Fox', 'Sub-Zero', 'Peter Jackson'),
('Millenium Fox', 'Liu Kang', 'Ed Boon')
) as x(publisher, movie, director)
)
select P.publisher
from (select distinct publisher, director from production) P
group by
P.publisher
having
count(p.Director) = 2 -- The directors should be exactly 2
and min(case when p.Director in ('Ben Affleck', 'Peter Jackson')
then 1 else 0 end) = 1
;
Correct Output, should show DC and Century Fox only. As they are the only publishers that employs both Ben Affleck and Peter Jackson exclusively.
| publisher |
| ----------- |
| Century Fox |
| DC |
Live test: https://www.db-fiddle.com/f/aDDw4Pd1DJzs6J5HgbKbdh/4