SQL检查查询结果中是否存在值

时间:2013-06-10 08:41:22

标签: sql sql-server sql-server-2008

以下查询返回仅具有territoryid = 200

的所有releaseID
select rt.ReleaseId from ReleaseTerritory rt 
group by rt.ReleaseId
having SUM(case when rt.TerritoryId=200 then 0 else 1 end)=0 

如何检查上面查询的结果中是否存在值 47033 。 非常感谢。

2 个答案:

答案 0 :(得分:3)

添加一个where子句,将返回的结果限制为特定的ReleaseId

select rt.ReleaseId from ReleaseTerritory rt
where rt.ReleaseId = 47033 
group by rt.ReleaseId
having SUM(case when rt.TerritoryId=200 then 0 else 1 end)=0

要接收yes or exists(警告未经测试的代码)之类的值:

select case when count(rt.ReleaseId) = 0 
then 'Doesnt Exist' 
else 'Exists' end as exists 
from ReleaseTerritory rt
where rt.ReleaseId = 47033 
group by rt.ReleaseId
having SUM(case when rt.TerritoryId=200 then 0 else 1 end)=0

答案 1 :(得分:0)

select ReleaseId from ReleaseTerritory
where ReleaseId = 47033
and TerritoryId=200
except
select ReleaseId from ReleaseTerritory 
where ReleaseId = 47033
and TerritoryId <> 200