以下查询旨在查找去医院的人数、去医院的总人数,然后将这两者相除以获得百分比。该表Claims
有 200 万多行,并且确实具有正确的非聚集索引patientid, admissiondate, and dischargdate
. 查询运行得足够快,但我对如何使它更有用很感兴趣。我希望能够在行中添加另一个代码,(hcpcs.hcpcs ='97001')
并将更改percentRehabNotHomeHealth
反映在另一列中。有没有可能不写一个大的、胖的连接语句来将两个查询的结果连接在一起?我知道通过添加额外的列,数学看起来不正确,但我现在并不担心。所需的示例输出:http: //imgur.com/BCLrd
数据库模式
select h.hospitalname
,count(*) as visitCounts
,hospitalcounts
,round(count(*)/cast(hospitalcounts as float) *100,2) as percentRehabNotHomeHealth
from Patient p
inner join statecounties as sc on sc.countycode = p.countycode
and sc.statecode = p.statecode
inner join hospitals as h on h.npi=p.hospitalnpi
inner join
--this join adds the hospitalCounts column
(
select h.hospitalname, count(*) as hospitalCounts
from hospitals as h
inner join patient as p on p.hospitalnpi=h.npi
where p.statecode='21' and h.statecode='21'
group by h.hospitalname
) as t on t.hospitalname=h.hospitalname
--this where exists clause gives the visitCounts column
where h.stateCode='21' and p.statecode='21'
and exists
(
select distinct p2.patientid
from Patient as p2
inner join Claims as c on c.patientid = p2.patientid
and c.admissiondate = p2.admissiondate
and c.dischargedate = p2.dischargedate
inner join hcpcs on hcpcs.hcpcs=c.hcpcs
inner join hospitals as h on h.npi=p2.hospitalnpi
where (hcpcs.hcpcs ='97001' or hcpcs.hcpcs='9339' or hcpcs.hcpcs='97002')
and p2.patientid=p.patientid
)
and hospitalcounts > 10
group by h.hospitalname, t.hospitalcounts
having count(*)>10