简体   繁体   中英

Select Multiple Values SQL

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 c an see a SQL Fiddle here ,

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;

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM