SQL陷入查询如何获取正确的数据

时间:2013-06-06 11:14:16

标签: 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.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

谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

将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)
    )

注意语句开头和结尾的附加括号 - 这些对于将OR本地化仅限于此语句非常重要,而不是使您的其余AND语句无效完整查询。

您还必须从WHERE子句中删除此语句,因为它只会将结果限制在这4个地区

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