0

My table looks something like this:

SQL TABLE

I want to retrieve all the PractitionerIdFK if they have SpecialityIdFK = 1 AND SpecialityIdFK= 2. I tried the following but it doesn't seem to work.

SELECT PractitionerSpecialities.PractitionerIdFK
FROM PractitionerSpecialities
WHERE PractitionerSpecialities.SpecialityIdFK IN (
        SELECT PractitionerSpecialities.SpecialityIdFK
        FROM PractitionerSpecialities
        WHERE PractitionerSpecialities.SpecialityIdFK = 1
            AND PractitionerSpecialities.SpecialityIdFK = 2
        )
2
  • 1
    Try or instead of and in your where clause since the SpecialityIdFK can't be both 1 and 2 at the same time. You could also do where PractitionerSpecialities.SpecialityIdFK IN (1, 2) Commented Jan 4, 2020 at 2:22
  • 1
    The subquery is unnecessary, Just change your IN expression as @MarkMoretto describes. Commented Jan 4, 2020 at 2:28

2 Answers 2

1

You can use GROUP BY and HAVING:

SELECT ps.PractitionerIdFK 
FROM PractitionerSpecialities ps
WHERE ps.SpecialityIdFK IN (1, 2)
GROUP BY ps.PractitionerIdFK 
HAVING COUNT(*) = 2;  -- the size of the comparison list

This assumes that there are no duplicates in PractitionerSpecialities. If that is a possibility, then use HAVING COUNT(DISTINCT ps.SpecialityIdFK) = 2.

Sign up to request clarification or add additional context in comments.

1 Comment

,In the question he\she doesn't ask about duplicate ,as per him he just want all PractitionerIdFK values for the SpecialityIdFK value 1 and 2
1

It can be achieved by using IN and BETWEEN operator in SQL .

SELECT  PractitionerSpecialities.PractitionerIdFK 
FROM PractitionerSpecialities
WHERE PractitionerSpecialities.SpecialityIdFK in (1,2)

-- You can BETWEEN Clause as well ..

SELECT  PractitionerSpecialities.PractitionerIdFK 
FROM PractitionerSpecialities
WHERE PractitionerSpecialities.SpecialityIdFK BETWEEN 1 AND 2 

In Sub query use OR operator instead of AND .

2 Comments

Maybe I am a little bit confused but what if I want to return ONLY the PractitionerIdFK if they have SpecialityIdFK 1 and 3? I don't want to display users who have SpecialityIdFK 1 or 3 but instead return users who meet the criteria of having SpecialityIdFK 1 and 3?
(1) I am baffled at what BETWEEN has to do with the question. (2) An upvote?

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.