SQL获取区域62和69但不在区域200和92中的数据

时间:2013-06-06 15:41:37

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

我想获取具有区域62和69但没有区域200和92的数据,我使用此查询但不起作用

select  rtp1.releaseId, rtp1.territoryId
from ReleaseTerritoryPrice rtp1
where rtp1.territoryId  in (62,69)
  and not exists (select releaseId
                  from ReleaseTerritoryPrice t2
                  where t2.territoryId in (200,92)
                    and rtp1.releaseId = t2.releaseId);

任何帮助? 感谢。

1 个答案:

答案 0 :(得分:2)

这是set-within-sets查询的示例。我喜欢使用带有having子句的聚合,因为这是一种非常灵活的方法:

select ReleaseId
from ReleaseTerritoryPrice
group by ReleaseId
having (sum(case when territoryId = 62 then 1 else 0 end) > 0 and
        sum(case when territoryId = 69 then 1 else 0 end) > 0
       ) and
       (sum(case when territoryId = 200 then 1 else 0 end) = 0 and
        sum(case when territoryId = 92 then 1 else 0 end) = 0
       )

having子句中的每个条件都计算每个地区的行数。前两个是说6269必须存在(计数大于1)。最后两个是说20092不存在(计数为0)。

例如,如果您想更改此设置,以便只需要6269中的一个而不是其他两个,则having子句将为:

having (sum(case when territoryId = 62 then 1 else 0 end) > 0 or
        sum(case when territoryId = 69 then 1 else 0 end) > 0
       ) and
       (sum(case when territoryId = 200 then 1 else 0 end) = 0 and
        sum(case when territoryId = 92 then 1 else 0 end) = 0
       )