使用子查询进行分组和聚合

时间:2012-08-01 17:35:03

标签: sql sql-server-2008 group-by

我的查询旨在查找多次去医院的人数。我有什么工作,但有没有办法在没有子查询的情况下做到这一点?

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

患者与医院之间简单的一对多关系

2 个答案:

答案 0 :(得分:2)

这是超级hacky,但在这里你是:

SELECT TOP 1 
    ROW_NUMBER() OVER (order by patient.patientid) as Count
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

答案 1 :(得分:0)

    select distinct hospitalname, count(*) over (partition by hospitalname) from (
    SELECT hospitalname, count(*) over (partition by   patientid,
    hospitals.hospitalname)   as counter
    FROM hospitals INNER JOIN
    Patient ON hospitals.npi = Patient.hospitalnpi
    WHERE     (hospitals.hospitalname = 'X')
    ) Z
    where counter > 1