1

I have a table where the data are as follow

ID Classroom Person
1   1         Alfred
2   1         Maria
3   2         Maria
4   2         Zoe
5   2         Alfred
6   3         Nick
7   3         Paul
8   3         Mike
9   3         Alfred
10  4         Zoe
11  4         Maria

I want to select and return only the Classroom that has as Person only 'Alfred' and 'Maria' Following statement :

Select * from table_name where (Person='maria') and (Person=Alfred')

doesn't seem to work.

You can see a SQL Fiddle here,

7
  • what effort have you made? Commented Dec 30, 2014 at 16:58
  • So are you trying to get the classroom numbers where both "Alfred" and "Maria" rows exist for that classroom? Commented Dec 30, 2014 at 16:59
  • Of course it doesn't work. There is no way a Person will be both 'Alfred' and 'Maria' on the same time. You want it be either 'Alfred' OR 'Maria'. Commented Dec 30, 2014 at 17:00
  • 1
    This is a legitimate (although very basic) question, wonder why the downvote? Commented Dec 30, 2014 at 17:03
  • 1
    @user3677132 Could you include the desired output? Commented Dec 30, 2014 at 17:03

2 Answers 2

3

You can use group by and having:

select classroom
from table t
group by classroom
having count(*) = 2 and
       sum(person in ('maria', 'Alfred')) = 2;

This assumes that one person cannot be in a classroom multiple times.

This checks that there are two names in the classroom and they are for the two names of interest. If you can have duplicates, you would want:

having count(distinct name) = 2 and
       count(distinct case when person in ('maria', 'Alfred') then person end) = 2;
Sign up to request clarification or add additional context in comments.

1 Comment

After a fast test it seems to be working. Thanks a lot Gordon.
2

Try this. Group by and having with Count should work.

SELECT Classroom
FROM   tablename
WHERE  Person IN( 'maria', 'Alfred' )
GROUP  BY classroom
HAVING Count(Person) = 2 

5 Comments

Not quite right . . . The OP appears to want only those two names in the classroom.
@GordonLinoff - Sorry i didn't get you. Even my query is doing the same thing.
. . Your query would pick up classroom = 2, because that has both the names, even though it also has Zoe.
. . I fixed your SQL Fiddle to have the data in the OP to demonstrate the issue: sqlfiddle.com/#!2/754405. But in simple terms, the where is executed before the having, so other names are never considered in the having. Your query is a correct answer to a very similar question.
@GordonLinoff - Yea sir you are right. Thanks for making me understand

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.