如何在满足子查询条件时只返回1行?

时间:2016-10-03 17:19:05

标签: sql sql-server sql-server-2008

我使用电子健康记录,需要确定符合特定标准的患者百分比。注意:由于数据来自EHR软件,因此我无法控制表格和字段的组织方式。

我的分母是所有符合某些标准的患者,例如:PatientDenominator(例如:所有患有XYZ123服务并且在2016年7月在特定州看过的患者)。我的分子是在PatientDenominator中有多少人在过去一年中检查了checkbox1或复选框2。

除非在每次访问时都不评估这些复选框,只能在某些访问时进行评估。所以我把它们作为子查询,但是因为我把它们放在FROM语句中,当患者满足这两个标准时,它们会返回两行,这会使分子偏斜(我现在在Excel中做的事情,因为我' m仍试图弄清楚查询。)

如何重新组织查询,以便我只能获得1行 - 当患者符合EITHER标准时?唯一的方法是我看到如何做一个CASE(当Scenario1 = 1然后1当Scenario2 = 1然后是1,否则为0)但这是最好的方法吗?我对这种复杂性感到陌生,因为我会一次评估几个月(每月约5000名患者),我对性能有点担心。

declare
  @startdate DATE,
  @enddate DATE

set  @startdate = '2016-07-01' 
set  @enddate = '2016-08-01'

select
  PatientNumber,
  PatientSex,
  case
    when (Scenario1='1' OR Scenario2='1') then 'Meets Criteria'
    when (checkbox1 is null and checkbox2 is null) then 'N/A'
    else 'Not Meet Criteria'
  end 'Criteria'
from
  PatientTable PT
  left join VisitTable VT on PT.person_id=VT.person_id
  left join LocationTable lt on VT.location_id=lt.location_id
  left join TableZ on VT.VisitID=TableZ.VisitID
  left join (
    select distinct
        PT1.person_id,
        case
          when TableA.checkbox1 = '1' OR TableB.checkbox2 = '1')
            then '1'
            else '0'
        end Scenario1Eval
    from 
        PatientTable1 PT1
        left join VisitTable1 VT1 on PT1.person_id=VT1.person_id
        left join TableA on VT1.VisitID=TableA.VisitID
        left join TableB on VT1.VisitID=TableB.VisitID
        left join TableC on VT1.VisitID=TableC.VisitID
    where
        sex='f'
        and TableC.VisitType in ('Type1','Type2')
        and (VT1.VisitDate > DATEADD(YEAR,-1,@startdate) and VT1.VisitDate  < @enddate )
    ) as Scenario1 on PT.person_id=Scenario1.person_id
  left join (
    select distinct
        PT2.person_id,
        case
            when TableA2.checkbox1 = '1' OR TableB2.checkbox2 = '1')
            then '1'
            else '0'
        end Scenario2Eval
    from 
        PatientTable1 PT2
        left join VisitTable1 VT2 on PT2.person_id=VT2.person_id
        left join TableA2 on VT2.VisitID=TableA2.VisitID
        left join TableB2 on VT2.VisitID=TableB2.VisitID
        left join TableD2 on VT2.VisitID=TableD2.VisitID
    where
        (VT1.VisitDate > DATEADD(YEAR,-1,@startdate) and VT1.VisitDate <    @enddate )
    and (TableD2.ChargeCode like '9920%' OR TableD2.ChargeCode like '9938%')) as Scenario2 on PT.person_id=Scenario2.person_id
  where
    VT1.VisitDate > @startdate and VT1.VisitDate < @enddate
    and TableZ.QualifyingField = 'Y'
    and lt.state='ZZ'
    and (Scenario1 is not null OR Scenario2 is not null)

0 个答案:

没有答案