我试图在每个月计算患者,我需要查看每月数字的结果,即使它是0。
我正在运行的查询应在其他月份的月份号13
和3
上提供0
。但正在发生的事情是13
被分割并分配到所有12个月,如下所示:
以下是查询:
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
答案 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 = 1
和year(date_app) = 2016
应放在ON
操作的LEFT JOIN
子句中,否则LEFT JOIN
变为INNER JOIN
。