检索仅具有两个特定值的记录

时间:2013-11-14 22:08:56

标签: sql squirrel-sql

表中包含以下数据

Example Table
ID  Value
1   a
1   b
1   c
2   a
2   b
2   c
3   a
3   b

我需要检索ID只有两个值a和b的记录。 所以我期待只有ID 3的记录。 任何人都可以帮我查询

2 个答案:

答案 0 :(得分:0)

我想你可以做点像

select
ID,
 sum(case when value = 'a' then 1
when value = 'b' then 1
else 3 end)

from 
table1
group by id
having
sum (case when value = 'a' then 1
when value = 'b' then 1
else 3 end) =2

SQL Fiddle

答案 1 :(得分:0)

这将有效:

select x.id from 
(
    select id from mytable where value = 'a'
    union all
    select id from mytable where value = 'b'
) x
group by x.id
having COUNT(*) = 2
and not exists (select * from mytable t where t.id = x.id and value <> 'a' and value <> 'b')