您的基本查询很好。您需要做的是将它们中的每一个都视为一个虚拟表,并将LEFT JOIN
它们放在一起。然后您的顶层SELECT
可以为您的整个表选择适当的值。
SELECT afftotal.date,
afftotal.centre_id,
afftotal.total AS total,
af20.total AS total_20,
afempty.total AS total_empty
FROM (
/* select total of affaires per month and per centre for this year */
select month(aff_date) AS `date`,
centre_id,
count(*) AS `total`
from affaires
where year(aff_date) = 2014
group by month(aff_date), centre_id
) AS afftotal
LEFT JOIN (
/* select total of affaires per month and per centre for this year where the affaire has been done
before 20 days. */
select month(`affaires`.`aff_date`) AS `date`,
centre_id,
count(*) AS `total`
from `affaires`
where year(`affaires`.`aff_date`) = 2014
and DATEDIFF(`affaires`.`aff_date`, `affaires`.`date_creation_pdl`) > 20
group by monthname(`affaires`.`aff_date`), centre_id
) AS af20 ON afftotal.date = af20.date
AND afftotal.centre_id = af20.centre_id
LEFT JOIN (
/* select total of affaires where the date_creation_pdl is empty */
select month(affaires.aff_date) as `date`,
centre_id,
count(*) as total
from affaires
where date_creation_pdl is null
and year(affaires.aff_date) = 2014
group by monthname(affaires.aff_date)
) AS afempty ON afftotal.date = afempty.date
AND afftotal.centre_id = afempty.centre_id
ORDER BY afftotal.centre_id, afftotal.date
http://sqlfiddle.com/#!2/d563e/24/0
请注意,这是按 center_id 和日期进行汇总的,因此您可以在单个查询中获取所有 center_id 值。
另请注意,该ORDER BY
子句位于整个查询的末尾。
你拥有的是三个子查询,如果你愿意的话,三个虚拟表,每一个都有三列:一个日期、一个 center_id 和一个总计。你LEFT JOIN
把它们中ON
的两列放在一起。
我不得不对您的查询进行一些处理,以使它们具有相似的列名和列数据格式,因此LEFT JOIN
操作具有常规结构。