0

下面的查询有点难看,所以我希望它的间距足够好以使其可读。如果他们来自某个地区,该查询会查找访问给定医院的人的百分比。例如,如果 X 县有 100 人居住,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' 之后的 (select count(*)..) 部分

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)
4

1 回答 1

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;
于 2012-07-20T21:04:51.360 回答