我有一个查询,旨在查找不止一次去医院的人数。我有什么工作,但是有没有办法在没有子查询的情况下做到这一点?
SELECT count(*) as counts, hospitals.hospitalname
FROM Patient INNER JOIN
hospitals ON Patient.hospitalnpi = hospitals.npi
WHERE (hospitals.hospitalname = 'X')
group by patientid, hospitalname
having count(patient.patientid) >1
order by count(*) desc
这将始终返回正确的行数(30),而不是数字 30。如果我删除了,group by patientid
那么我会返回整个结果集。
我通过这样做解决了这个问题
select COUNT(*),hospitalname
from
(
SELECT count(*) as counts,hospitals.hospitalname
FROM hospitals INNER JOIN
Patient ON hospitals.npi = Patient.hospitalnpi
group by patientid, hospitals.hospitalname
having count(patient.patientid) >1
) t
group by t.hospitalname
order by t.hospitalname desc
我觉得必须有一个比一直使用子查询更优雅的解决方案。如何改进?
sample data from first query
row # revisits
1 2
2 2
3 2
4 2
same data from second, working query
row# hosp. name revisitAggregate
1 x 30
2 y 15
3 z 5
患者和医院之间简单的一对多关系