SQL Server:查找存在一个条目但缺少另一个条目的人员记录

时间:2015-11-12 22:58:47

标签: sql-server

我正在尝试从我们的表中提取数据,以显示包含一个服务项的每个人记录,但不包括另一个服务项。我想要所有'person_id'记录,其中有一个服务项目为66984但没有附加92136的服务项目。对于每个person_id,每个附加的服务项有多个条目。这是我正在尝试的代码,但它出现了空白:

select person_id, service_item_id from charges
where exists (SELECT person_id from charges where service_item_id = '66984') 
and not exists (SELECT person_id from charges where service_item_id = '92136')
order by person_id

更进一步,我希望一次检查多个代码。所以它检查92136或76519是否不存在并返回所有具有66984但没有其他代码的person_ids

谢谢!

1 个答案:

答案 0 :(得分:0)

关闭,您需要在子查询中添加person_id

select person_id, service_item_id from charges  
where exists (SELECT person_id from charges c1 where charges.person_id = c1.person_id and service_item_id = '66984') 
and not exists (SELECT person_id from charges c2 where charges.person_id = c2.person_id and service_item_id = '92136')
order by person_id