I have two tables that look like this:
Supplier
SN SNAME Stat City
+----------+-------+----+--------+
| S1 | Smith | 20 | London |
| S2 | Jones | 10 | Paris |
| S3 | Blake | 30 | Paris |
| S4 | Clark | 20 | London |
| S5 | Adams | 30 | Athens |
+----------+-------+----+--------+
Shipment
SN PN QTY
+----+----+-----+
| S1 | P1 | 300 |
| S1 | P2 | 200 |
| S1 | P3 | 400 |
| S1 | P4 | 200 |
| S1 | P5 | 100 |
| S1 | P6 | 100 |
| S2 | P1 | 300 |
| S2 | P2 | 400 |
| S3 | P2 | 200 |
| S4 | P2 | 200 |
| S4 | P4 | 300 |
| S4 | P5 | 400 |
+----+----+-----+
I have the find the following:
List the supplier names (SNAME) for those suppliers who ship at least all those parts (PN) supplied by supplier S2.
In other words, I need to list all those suppliers who ship at least P1 and P2, although obviously my query needs to be focused more on the question at hand.
I’m pretty sure I have to use some form of NOT EXISTS — perhaps the double not exists, to achieve this. I tried doing a self-join of the Shipment table to itself — but I can’t understand how to get it beyond checking for ANY item that appears in the PN for S2 and instead check to make sure ALL parts for S2 are in the list before including the name in the result.
I used a Common Table Expression to accomplish this:
If you do not want to use the CTE, you can use subqueries instead: