或者查询无效

时间:2014-07-29 20:13:12

标签: sql

我遇到了最后一个选择语句OR的问题。我们想要的是包括 具有TIER = T1的记录,但仅当具有COST> 500和skilllevel ='S'。但是这行的最后一行只需要是一个OR。 AND将遗漏大部分记录。

 Insert Into @tblMain
    Select  * from (
            SELECT distinct a.ID_KEY,a.STAT, a.TIER, f.FACILITY_ID,  f.FACILITY_NAME Name, a.RX, a.PATIENTNAME, a.MEDICATION , (a.COST) as Cost, (a.COST) as Interchanges,  s.Savings Savings
            FROM[PBM].[T_CHARGES] a 
            --Inner Join  PBM.FACILITY f on a.FACILITYNPI = f.FACILITY_NPI 
            inner Join PBM.PHARMACY_NPI pn on a.PHARMACYNPI = pn.NPI
            Inner join PBM.PHARMACY_FACILITY pp on pn.PHARMACY_ID = pp.PHARMACY_ID
            inner Join PBM.FACILITY f on pp.FACILITY_ID = f.FACILITY_ID AND a.FACILITYNPI = f.FACILITY_NPI
            Left Outer Join @TableSum s on a.ID_KEY = s.ID_KEY 
            where f.FACILITY_NAME is not null 
            and month(a.DATEDISPENSED) = @Month and year(a.DATEDISPENSED) = @Year        
            and f.FACILITY_ID = @FacilityId
            and a.STAT not in (3,4,5) 
             and (TIER <> 'T1' )
            --OR (TIER = 'T1' AND COST>500 AND SKILLLEVEL = 'S' )       

3 个答案:

答案 0 :(得分:5)

默认情况下,sql server NOT优先于ANDAND优先于OR

   NOT --> AND --> OR 

要强制执行默认订单以外的订单,您可以使用括号。

...........
and f.FACILITY_ID = @FacilityId
and a.STAT not in (3,4,5) 
and (  
          (TIER <> 'T1') 
       OR 
          (TIER = 'T1' AND COST > 500 AND SKILLLEVEL = 'S' )
    )    

答案 1 :(得分:5)

SQL Server将尊重评估顺序的括号,我认为您需要:

...
AND 
(
   (TIER <> 'T1')
   OR 
   (TIER = 'T1' AND COST>500 AND SKILLLEVEL = 'S')
)

答案 2 :(得分:4)

您需要添加括号。您也可以删除TIER = 'T1'子条件,因为如果TIER不是'T1',则对<>的检查会成功,从而OR {{1}无论额外检查如何:

true