0

I'm trying to learn SQL and I'm having a little trouble here.

 ID  |  P_Id |  room | 
======================
 1   |   8   |   A   |
 2   |   8   |   A   |
 3   |   8   |   B   |
 4   |   9   |   B   |
 5   |   9   |   B   |
 6   |   10  |   C   |
 7   |   10  |   C   |
 8   |   10  |   D   |

I'm trying to figure out which P_Id has only worked in room B. So the outcome would be P_Id = 9. Not 8 as well, because he worked in room A as well.

This is my query, but it doesn't work:

SELECT Room.P_Id
FROM Room
WHERE NOT EXISTS (SELECT *
                  FROM Room
                  WHERE Room.room <> 'B');

Could you guys help me out here?

4 Answers 4

2

You need to correlate the subquery with the outer query and use different aliases in the outer and inner queries, or the subquery will use the wrong table. The correlation makes sure the subquery applies to the correct row in the outer query (where the P_Id matches).

Do this instead:

SELECT DISTINCT r1.P_Id
FROM Room r1
WHERE NOT EXISTS (
  SELECT *
  FROM Room r2
  WHERE r2.room <> 'B'
    AND r1.P_Id = r2.P_Id
);
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

Select distinct p_ID 
from room 
where room = 'B' 
  and p_id not in (Select p_ID from room where room <> 'B')

Comments

0

How about this:

Select Room.P_Id
FROM Room
WHERE MIN(room.room) = MAX(room.room) and MIN(room.room) = 'B'
Group by Room.P_Id

There might be other more elegant ways, but this will get the job done.

Comments

0

You can also try

SELECT DISTINCT P_Id FROM Room WHERE NOT EXISTS (SELECT P_Id FROM Room WHERE room <>'B');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.