我遇到mysql查询问题, 事实上,我必须构建一个包含图表的网页,我需要从数据库中获取数据,如下所示:
1-获取当前年度每个中心(每个中心(平均国家))收到的数据总数
2-获取当前每年中心未完成的数据总数
3-获取尚未完成的数据总数以及当前年度每个中心每月超过20天的数据。
所以,总而言之,我能够获取所有thoses查询的数据,没问题。 我面临的问题是,我需要将这些查询嵌入到单个查询中,然后返回一个类似的表:
| monthname | total | totalNotDone | totalExceed20Days |
| January | 52 | 3 | 1 |
| February | 48 | 4 | 0 |
| March | 54 | 1 | 3 |
等
这是一个显示问题的平方小说:
已编辑:http://sqlfiddle.com/#!2/8cc9c/1
任何帮助都会非常感谢大家,我真的被卡住了。
答案 0 :(得分:0)
您的基本查询没问题。您需要做的是将它们作为虚拟表格,并将它们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
请注意,这是通过centre_id和date汇总的,因此您可以在一个查询中获取所有centre_id值。
另请注意,ORDER BY
子句位于整个查询的末尾。
你有三个子查询,三个虚拟表,如果你愿意,每个有三列:一个日期,一个centre_id和一个总数。您LEFT JOIN
他们一起ON
其中两列。
我不得不捣乱你的查询,使它们具有相似的列名和列数据格式,因此LEFT JOIN
操作具有常规结构。