我有下面提到的表:
ID Value
KA-1 A
KA-1 B
KA-1 C
KA-1 D
KA-2 A
KA-2 C
KA-2 C
KA-2 D
KA-3 C
KA-3 B
我想取这些ID
,其中至少有一个对应的值是D
但是相同的ID
没有值B
。
要求输出:
ID
KA-2
一个简单的解决方案是:
select distinct id from table
where value='D' and id not in (select distinct id from table where value='B')
SELECT ID
FROM YOUR_TABLE
GROUP BY ID
HAVING SUM(VALUE='D')>=1 AND SUM(VALUE='B')=0;
看到一个有效的DEMO on SQL Fiddle。
您可以尝试使用exists而不存在:
select id
from table1 as a
where exists (select *
from table1 b
where b.value='D' and b.id=a.id)
and not exists (select *
from table1 c
where c.value='B' and c.id=a.id)