我想获取具有区域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);
任何帮助? 感谢。
答案 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
子句中的每个条件都计算每个地区的行数。前两个是说62
和69
必须存在(计数大于1)。最后两个是说200
和92
不存在(计数为0)。
例如,如果您想更改此设置,以便只需要62
和69
中的一个而不是其他两个,则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
)