SQL查询 - GROUP BY内的计数没有结果

时间:2017-11-15 06:05:30

标签: mysql sql sql-server subquery

我想计算每个市的患者诊断和每个市的咨询:

所以它应该是:

每个市的诊断+每个市的咨询

SELECT COUNT(consultations.id) + 
(SELECT COUNT(patientdiagnosis.id) 
    FROM consultations 
    LEFT JOIN patientdiagnosis 
    ON patientdiagnosis.consultation_id = consultations.id
    LEFT JOIN patients
    ON consultations.patient_id = patients.id
    LEFT JOIN rcitymun
    ON patients.municipality = rcitymun.citycode 
    /*GROUP BY PER MUNICIPALITY SHOULD BE HERE*/
) as encounters, rcitymun.cityname
FROM consultations 
LEFT JOIN patients
ON consultations.patient_id = patients.id
LEFT JOIN rcitymun
ON patients.municipality = rcitymun.citycode
GROUP BY patients.municipality;

当前输出:

encounters         municipality
10323                 BATAC
10423                 NUEVA ERA

遇到的数据是巨大的,因为它计算的是所有的诊断,而不是每个市政当局

我想要的是统计每个城市的诊断。

所需的输出是这样的:

encounters         municipality
105                   BATAC
70                   NUEVA ERA

1 个答案:

答案 0 :(得分:1)

可以通过一个子查询来减少这个,但通常最好从独立分组的子查询开始。

SELECT
       rcitymun.cityname
     , SUM(c.consult_count) consult_count
     , SUM(d.diag_count) diag_count
FROM patients
INNER JOIN rcitymun ON patients.municipality = rcitymun.citycode
LEFT JOIN (
      SELECT
            consultations.patient_id
          , COUNT(*) consult_count
      FROM consultations
      GROUP BY
            consultations.patient_id 
) c ON patients.id = c.patient_id
LEFT JOIN (
      SELECT
            consultations.patient_id
          , COUNT(*) diag_count
      FROM consultations
      INNER JOIN patientdiagnosis ON patientdiagnosis.consultation_id = consultations.id
      GROUP BY
            consultations.patient_id
) d ON patients.id = d.patient_id
GROUP BY
       rcitymun.cityname