0

这两个查询都做同样的事情,其中​​一个的运行速度大约是另一个的 2.5 倍

慢查询

select sc.countyName
        ,(
    --this adds the distinct number of people who received rehab    
    select count(distinct p2.patientid)
        from statecounties as sc2
        inner join Patient as p2 on p2.stateCode=sc2.stateCode
        and p2.countyCode = sc2.countyCode
        and sc2.stateCode='21'
        inner join Claims as c on c.patientid=p2.patientid
        and c.admissiondate = p2.admissiondate
        and c.dischargedate = p2.dischargedate
        where sc2.countyName=sc.countyname and c.hcpcs in ('97001', '9339', '97002')

     ) as rehabClaims
     --this is the total number of people from each county that visited a hospital with a DRG stroke admission
     ,count(*) as visitCounts
     ,(
    --this adds the distinct number of people who received rehab    
    select count(distinct p2.patientid)
        from statecounties as sc2
        inner join Patient as p2 on p2.stateCode=sc2.stateCode
        and p2.countyCode = sc2.countyCode
        and sc2.stateCode='21'
        inner join Claims as c on c.patientid=p2.patientid
        and c.admissiondate = p2.admissiondate
        and c.dischargedate = p2.dischargedate
        where sc2.countyName=sc.countyname and c.hcpcs in ('97001', '9339', '97002')

     )/count(*) as visitCounts
     from StateCounties as sc
    inner join Patient as p on p.stateCode=sc.stateCode
    and p.countyCode=sc.countyCode
    where sc.stateCode='21'
    group by sc.countyName
    having count(*) > 30

快速查询

select *, round(cast(rehabclaims as float)/VisitCounts *100,2) as percentRehab
from
(
select sc.countyName
        ,(
    --this adds the distinct number of people who received rehab    
    select count(distinct p2.patientid)
        from statecounties as sc2
        inner join Patient as p2 on p2.stateCode=sc2.stateCode
        and p2.countyCode = sc2.countyCode
        and sc2.stateCode='21'
        inner join Claims as c on c.patientid=p2.patientid
        and c.admissiondate = p2.admissiondate
        and c.dischargedate = p2.dischargedate
        where sc2.countyName=sc.countyname and c.hcpcs in ('97001', '9339', '97002')

     ) as rehabClaims
     --this is the total number of people from each county that visited a hospital with a DRG stroke admission
    ,count(*) as visitCounts
    from StateCounties as sc
    inner join Patient as p on p.stateCode=sc.stateCode
    and p.countyCode=sc.countyCode
    where sc.stateCode='21'
    group by sc.countyName
    having count(*) > 30
) t

主要区别在于第一个中的除法是在sub selects他们自己身上完成的,而在更快的查询中它使用子查询(如果我的行话错误,请道歉)。我更喜欢第二种方式,因为它更容易阅读 columnName/otherColumnName 而不是输入整个表达式。似乎这种情况通常也更快。这是有原因的,还是只是轶事(适用适当的索引)

4

0 回答 0