获得较大群体的百分比

时间:2012-07-20 19:41:16

标签: sql sql-server-2008 tsql

下面的查询有点难看,所以我希望我的间隔足够好以使其可读。查询查找访问给定医院的人员百分比,如果他们来自某个区域。例如,如果100个人住在X县,20个住院A,80个住院B,查询输出。这种事情到底怎么了?如果我需要记录查询或我能做些什么来让它更清楚,请告诉我。

hospital A 20
hospital B 80

下面的查询与我想要的完全一样,但它让我思考:如何才能为我表中的每个县做这件事?

select  hospitalname, round(cast(counts as float)/cast(fayettestrokepop as float)*100,2)as percentSeen
from
(

SELECT     tblHospitals.hospitalname, COUNT(tblHospitals.hospitalname) AS counts, tblStateCounties_1.countyName,
                          (SELECT     COUNT(*) AS Expr1
                            FROM          Patient INNER JOIN
                                                   tblStateCounties ON Patient.stateCode = tblStateCounties.stateCode AND Patient.countyCode = tblStateCounties.countyCode
                            WHERE      (tblStateCounties.stateCode = '21') AND (tblStateCounties.countyName = 'fayette')) AS fayetteStrokePop
FROM         Patient AS Patient_1 INNER JOIN
                      tblHospitals ON Patient_1.hospitalnpi = tblHospitals.hospitalnpi INNER JOIN
                      tblStateCounties AS tblStateCounties_1 ON Patient_1.stateCode = tblStateCounties_1.stateCode AND Patient_1.countyCode = tblStateCounties_1.countyCode
WHERE     (tblStateCounties_1.stateCode = '21') AND (tblStateCounties_1.countyName = 'fayette')
GROUP BY tblHospitals.hospitalname, tblStateCounties_1.countyName

) as t 
order by percentSeen desc

编辑:示例数据 下面的示例数据没有最外层的查询(as t order by部分)。

countsInTheCounty列是'tblStateCounties_1.countyName'之后的(选择计数(*)..)部分

hospitalName      hospitalCounts      countyName      countsInTheCounty
st. james          23                 X               300
st. jude           40                 X               300

现在有了外部查询,我们会得到

st james  0.076 (23/300)
st. jude  0.1333 (40/300)

1 个答案:

答案 0 :(得分:1)

这是我的猜测。您必须测试您的数据或提供正确的DDL +样本数据。

;WITH totalCounts AS 
(
  SELECT StateCode, countyCode, COUNT(*) AS totalcount
  FROM dbo.Patient GROUP BY StateCode, countyCode
)
SELECT 
  h.hospitalName, 
  hospitalCounts = COUNT(p.hospitalnpi), 
  c.countyName, 
  countsInTheCounty = tc.totalCount, 
  percentseen = CONVERT(DECIMAL(5,2), COUNT(p.hospitalnpi)*100.0/tc.totalCount)
FROM 
  dbo.Patient AS p
INNER JOIN 
  dbo.tblHospitals AS h
  ON p.hospitalnpi = h.hospitalnpi
INNER JOIN 
  totalCounts AS tc
  ON p.StateCode = tc.StateCode
  AND p.countyCode = tc.countyCode
INNER JOIN 
  dbo.tblStateCounties AS c
  ON tc.StateCode = c.stateCode
  AND tc.countyCode = c.countyCode
GROUP BY 
  h.hospitalname, 
  c.countyName, 
  tc.totalcount
ORDER BY
  c.countyName,
  percentseen DESC;