0

我有一个mysql查询的问题,实际上我必须用图表构建一个网页,我需要从数据库中获取数据,如下所示:

1-获取当年每个中心(即国家)每月收到的数据总量,

2-获取本年度每个中心每月未完成的数据总数,

3- 获取当前年度每个中心每月未完成且日期超过 20 天的数据总数。

所以,总而言之,我能够为所有这些查询获取数据,这没有问题。我面临的问题是,我需要将这些查询嵌入到 1 个单个查询中,返回一个这样的表:

| monthname | total | totalNotDone | totalExceed20Days |
|  January  | 52    |    3         |      1            |
|  February | 48    |    4         |      0            |
|  March    | 54    |    1         |      3            |

等等

这是一个显示问题的sqlfiddle:

编辑:http ://sqlfiddle.com/#!2/8cc9c/1

任何帮助将不胜感激,我真的被困住了。

4

1 回答 1

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

请注意,这是按 center_id 和日期进行汇总的,因此您可以在单个查询中获取所有 center_id 值。

另请注意,该ORDER BY子句位于整个查询的末尾。

你拥有的是三个子查询,如果你愿意的话,三个虚拟表,每一个都有三列:一个日期、一个 center_id 和一个总计。你LEFT JOIN把它们中ON的两列放在一起。

我不得不对您的查询进行一些处理,以使它们具有相似的列名和列数据格式,因此LEFT JOIN操作具有常规结构。

于 2014-06-23T18:58:00.133 回答