加入标准优先问题

时间:2016-02-08 18:22:36

标签: sql

Hello Stack overflow community,

我是SQL的新手,所以我可能会忽略一些简单的东西。 出于某种原因,当我将t2标准添加到WHERE子句时,t1。标准不再遵循。 例如,当我在没有诊断规范的情况下运行查询时,我只看到指定的AdmitDateTimes之间的住院患者,这些患者年龄在18岁以上。但是,当我添加诊断标准时,我的联合表具有任何状态的患者,来自任何AdmitDateTime和任何年龄。

非常感谢任何和所有的帮助

谢谢!

SELECT TOP 1000 
       ReportTraining.dbo.IatricGetAge(t1.BirthDateTime,t1.ServiceDateTime) AS 'Age'
      ,t1.[SourceID]
      ,t1.[VisitID]
      ,t1.[AbstractStatusDateTime]
      ,t1.[AccountNumber]
      ,t1.[AdmitDateTime]
      ,t1.[AdmitFromEr]
      ,t1.[BirthDateTime]
      ,t1.[DischargeDateTime]
      ,t1.[DischargeDispositionID]
      ,t1.[DischargeDispositionName]
      ,t1.[FacilityID]
      ,t1.[FacilityName]
      ,t1.[LocationID]
      ,t1.[LocationName]
      ,t1.[Name]
      ,t1.[ObservationDateTime]
      ,t1.[ObservationPatient]
      ,t1.[PatientStatusName]
      ,t1.[PtStatus]
      ,t1.[ReasonForVisit]
      ,t1.[ServiceDateTime]
      ,t1.[Status]
      ,t1.[UnitNumber]
      ,t1.[RowUpdateDateTime]
      ,t1.[AbstractID]
      ,t1.[PatientID]
      ,t2.[VisitID]
      ,t2.[DiagnosisSeqID]
      ,t2.[Diagnosis]
      ,t2.[AbstractID]
  FROM  [Livedb].[dbo].[AbstractData] t1
        INNER JOIN [Livedb].[dbo].[AbsDrgDiagnoses] t2      ON (t2.AbstractID = t1.AbstractID   AND
                                                                t2.VisitID    = t1.VisitID)

  WHERE t1.AdmitDateTime BETWEEN '2016-01-01' AND '2016-01-31' AND
  t1.PatientStatusName LIKE 'INPATIENT' AND
  ReportTraining.dbo.IatricGetAge(t1.BirthDateTime,t1.ServiceDateTime)>= '18' AND
  t2.Diagnosis IN ('G62.1' , 'I42.6' , 'K29.2' , 'K70' , 'T39' , 'T40' , 'T41.3' , 'T51.91XA' , 'Z71.41' , 'Z72.51') OR
  t2.Diagnosis LIKE 'F%'       AND
  t2.Diagnosis NOT LIKE 'F01%' AND
  t2.Diagnosis NOT LIKE 'F02%' AND
  t2.Diagnosis NOT LIKE 'F03%' AND
  t2.Diagnosis NOT LIKE 'F17%' AND
  t2.Diagnosis NOT LIKE 'F70%' AND
  t2.Diagnosis NOT LIKE 'F71%' AND
  t2.Diagnosis NOT LIKE 'F72%' AND 
  t2.Diagnosis NOT LIKE 'F73%' AND
  t2.Diagnosis NOT LIKE 'F74%' AND
  t2.Diagnosis NOT LIKE 'F75%' AND 
  t2.Diagnosis NOT LIKE 'F76%' AND
  t2.Diagnosis NOT LIKE 'F77%' AND
  t2.Diagnosis NOT LIKE 'F78%' AND
  t2.Diagnosis NOT LIKE 'F79%';

1 个答案:

答案 0 :(得分:3)

AND之前评估

OR - 每当你混合它们时,你应该添加括号以确保你的条件被适当地分组。在您的情况下,您可能需要对两个OR条件进行分组,以便将它们评估为一个组:

WHERE ... AND ... AND ...
   AND
   (  t2.Diagnosis IN (...) OR
      t2.Diagnosis LIKE 'F%'    
   )
   AND
       ....