计算每个月的患者数

时间:2016-03-17 15:12:11

标签: mysql

我试图在每个月计算患者,我需要查看每月数字的结果,即使它是0。

我正在运行的查询应在其他月份的月份号133上提供0。但正在发生的事情是13被分割并分配到所有12个月,如下所示:

enter image description here

以下是查询:

SELECT 
    count(patients) as patients, month

FROM 
(
    SELECT 
        count(app_id) as patients, 
        month(date_app) as month 
    FROM 
        dentist.appointment
    WHERE id_logged=1 AND year(date_app)='2016'
    GROUP BY month(date_app)

    UNION SELECT 0,1
    UNION SELECT 0,2
    UNION SELECT 0,3
    UNION SELECT 0,4
    UNION SELECT 0,5
    UNION SELECT 0,6
    UNION SELECT 0,7
    UNION SELECT 0,8
    UNION SELECT 0,9
    UNION SELECT 0,10
    UNION SELECT 0,11
    UNION SELECT 0,12
) tmp
GROUP BY month

1 个答案:

答案 0 :(得分:1)

尝试此查询:

SELECT 
    count(app_id) as patients, 
    t.m as month 
FROM (    
   SELECT 1 AS m UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION
   SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION
   SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS t
LEFT JOIN dentist.appointment ON t.m = month(date_app) AND
          id_logged = 1 AND year(date_app) = 2016
GROUP BY t.m

诀窍是首先创建一个内嵌表,其中包含所有12个月的数字,然后 LEFT JOIN将原始表格添加到内联表格中。

注意:谓词id_logged = 1year(date_app) = 2016应放在ON操作的LEFT JOIN子句中,否则LEFT JOIN变为INNER JOIN

Demo here