- The first select in the with clause is a join of tables.
- The second select uses the first select and finds the id whose column "Data" takes all the values from the output column of table A.
- The third select contains only the ids without the "Data" in table A.
- The result contains only ids that have all outputs and no extra.
- Unique values in both tables are prerequisites.
- Oracle 11RG2.
DDL:
CREATE TABLE TableA
("OUTPUT" varchar2(1))
;
INSERT ALL
INTO TableA ("OUTPUT")
VALUES ('A')
INTO TableA ("OUTPUT")
VALUES ('B')
SELECT * FROM dual
;
CREATE TABLE TableB
("ID" int, "Data" varchar2(1))
;
INSERT ALL
INTO TableB ("ID", "Data")
VALUES (1, 'A')
INTO TableB ("ID", "Data")
VALUES (1, 'B')
INTO TableB ("ID", "Data")
VALUES (1, 'C')
INTO TableB ("ID", "Data")
VALUES (2, 'A')
INTO TableB ("ID", "Data")
VALUES (2, 'B')
INTO TableB ("ID", "Data")
VALUES (3, 'B')
INTO TableB ("ID", "Data")
VALUES (3, 'C')
INTO TableB ("ID", "Data")
VALUES (3, 'D')
SELECT * FROM dual
;
SQL:
with a (id, "Data", output) as (
select
id, "Data", output
from
tableb left join tablea on "Data"=output
)
select
id
from
a
where
output is not null
group by id
having count("Data") = (select count(output) from tablea)
minus
select id from a where output is null
;
Output: