SQL卡在如何获取正确数据的查询中

SQL卡在如何获取正确数据的查询中,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,在这个查询中,我试图获取31、41、125、201地区价格相同的值(主要是r.dpq),其中价格应为922,而所有其他地区的价格应为216 该查询确实捕获了在31、41、125、201地区价格为216的产品,但在其他地区没有。我猜错误在这里,但我不知道如何更正它 rte.TerritoryId not in (31,41,201,125) and rte.PriceCodeId=216 and rte.PartnerTerritoryId is null 这是完整的查询 select r.dp

在这个查询中,我试图获取31、41、125、201地区价格相同的值(主要是r.dpq),其中价格应为922,而所有其他地区的价格应为216

该查询确实捕获了在31、41、125、201地区价格为216的产品,但在其他地区没有。我猜错误在这里,但我不知道如何更正它

rte.TerritoryId not in (31,41,201,125) and rte.PriceCodeId=216 and rte.PartnerTerritoryId is null
这是完整的查询

select r.dpq, r.OwningTerritoryId , r.id from Release r
inner join ReleaseTerritory rt on rt.ReleaseId=r.Id
inner join ReleaseTerritoryPrice rtp on rtp.ReleaseId=r.Id
where exists (
select * from ReleaseTerritoryPrice rtp31, ReleaseTerritoryPrice rtp201,ReleaseTerritoryPrice rtp41,ReleaseTerritoryPrice rtp125,
ReleaseTerritory rt69 , ReleaseTerritoryPrice rte
where 
rtp31.ReleaseId=r.Id and rtp201.ReleaseId=r.Id and rtp41.ReleaseId=r.Id and rtp125.ReleaseId=r.Id and rt69.ReleaseId=r.Id and 
rte.ReleaseId=r.Id and 
rtp31.TerritoryId=31 and rtp201.TerritoryId=201 and rtp41.TerritoryId=41 and rtp125.TerritoryId=125 and 
rtp31.PriceCodeId=rtp201.PriceCodeId and rtp201.PriceCodeId=rtp41.PriceCodeId and rtp41.PriceCodeId=rtp125.PriceCodeId and 
rt69.TerritoryId=69 and 
rtp31.PriceCodeId=922 and 
rt69.IsLocked=0 and 
rte.TerritoryId not in (31,41,201,125) and rte.PriceCodeId=216 and rte.PartnerTerritoryId is null
) and r.OwningTerritoryId in (201,200)
group by r.dpq , r.OwningTerritoryId , r.Id
order by r.OwningTerritoryId

感谢您的帮助

将where子句的最后一部分修改为:

AND (
       (rte.TerritoryId IN (31,41,201,125) AND rte.PriceCodeId = 922)     
        OR
       (rte.TerritoryId NOT IN (31,41,201,125) AND rte.PriceCodeId = 216)
    )
注意语句开头和结尾的附加括号-这些括号对于仅保留或本地化到此语句非常重要,而不是在完整查询中使其余的
语句无效

您还必须从WHERE子句中删除该语句,因为它将结果仅限于这4个区域

rtp31.TerritoryId=31 and rtp201.TerritoryId=201 
and rtp41.TerritoryId=41 and rtp125.TerritoryId=125 

我认为你提到的过滤器不符合你的要求。可能是

(rte.TerritoryId not in (31,41,201,125) and rte.PriceCodeId=216) or
(rte.TerritoryId not (31,41,201,125) and rte.PriceCodeId=922)

我们的回答是否有助于您解决问题?