我有一张数据如下的表
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
我想选择并仅返回仅以人为主的课堂' Alfred'和玛丽亚' 以下声明:
Select * from table_name where (Person='maria') and (Person=Alfred')
似乎不起作用。
答案 0 :(得分:3)
您可以使用group by
和having
:
select classroom
from table t
group by classroom
having count(*) = 2 and
sum(person in ('maria', 'Alfred')) = 2;
这假设一个人不能多次在教室里。
这会检查课堂上有两个名字,它们是两个感兴趣的名字。如果你有重复项,你可能需要:
having count(distinct name) = 2 and
count(distinct case when person in ('maria', 'Alfred') then person end) = 2;
答案 1 :(得分:2)
试试这个。 Group by and having
Count
应该有效。
SELECT Classroom
FROM tablename
WHERE Person IN( 'maria', 'Alfred' )
GROUP BY classroom
HAVING Count(Person) = 2