SQL选择具有公共值的组

时间:2014-04-22 19:16:27

标签: sqlite

我正在摸索如何做这个选择。

表(GroupID,参与者)
g1,A
g1,B
g2,A
g2,C
g3,A
g3,B
g3,C
g4,A
g4,B
g4,C
g4,D

我想选择只有A,B,C共享的GroupID(在这种情况下,将是g3)。请注意,我不想要g4,因为我想要只有A,B,C所在的GroupID。任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

这将选择至少有3个不同groupid

participants
select groupid
from your_table
group by groupid
having count(distinct participants) >= 3

要明确A,B,C,您可以

select groupid
from your_table
where participants in ('A','B','C')
group by groupid
having count(distinct participants) = 3

如果您不想要任何其他参与者,那么

select groupid
from your_table
group by groupid
having sum(participants = 'A') > 0
and sum(participants = 'B') > 0
and sum(participants = 'C') > 0
and sum(participants not in ('A','B','C')) = 0

select groupid
from your_table
group by groupid
having sum(participants not in ('A','B','C')) = 0
and count(distinct participants) = 3