-1

表中有以下数据

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 的记录。谁能帮我查询

4

2 回答 2

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小提琴

于 2013-11-14T22:17:20.333 回答
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')
于 2013-11-14T22:17:53.960 回答