gpt4 book ai didi

mysql嵌套查询有4个查询

转载 作者:行者123 更新时间:2023-11-30 00:07:44 25 4
gpt4 key购买 nike

我的 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

任何帮助将不胜感激,伙计们,我真的很困难。

最佳答案

您的基本查询没问题。您需要做的是将它们中的每一个视为一个虚拟表,并将它们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 操作具有规则的结构。

关于mysql嵌套查询有4个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24372897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com