SQL在同一个表中发现缺少针对多个ID的特定字符串

时间:2018-01-23 14:34:26

标签: sql

ID  can eat
1   apples
1   pears
2   grapes
2   pears
3   apples
3   oranges
3   pears
4   oranges
5   apples
6   pears
6   oranges

使用上表作为数据示例。如何找到所有不能吃苹果的人的身份证?

4 个答案:

答案 0 :(得分:1)

id分组,只收集那些没有apples条目的群组

select id
from your_table
group by id
having sum(case when can_eat = 'apples' then 1 else 0 end) = 0

答案 1 :(得分:1)

只需选择id except可以吃苹果的人:

select id from tablename
except
select id from tablename where caneat = 'apples'

答案 2 :(得分:0)

SELECT Sheet1.ID
FROM Sheet1 LEFT JOIN (SELECT Sheet1.ID
FROM Sheet1
WHERE (((Sheet1.caneat)="apples"))
GROUP BY Sheet1.ID)  AS CanEatApplesList ON Sheet1.ID = CanEatApplesList.ID
WHERE (((CanEatApplesList.ID) Is Null))
GROUP BY Sheet1.ID;

答案 3 :(得分:0)

这是最简单的可能解决方案之一:

SELECT DISTINCT a.ID
FROM TableName a
WHERE can_eat NOT in ('apples') 
AND a.ID NOT in (SELECT distinct b.ID
FROM TableName b WHERE b.can_eat = 'apples');