gpt4 book ai didi

Mysql 近12个月按月记录总和

转载 作者:行者123 更新时间:2023-11-29 01:59:07 25 4
gpt4 key购买 nike

您好,我正在使用此 sql 查询获取基于图表表示月份的最近 12 个月的记录:

SELECT DATE_FORMAT(drives.timestamp, "%b") AS Month,
DATE_FORMAT(drives.timestamp, "%d-%m-%Y %H:%i:%s") AS Exact_date,
drives.departure,
drives.destination,
drives.route,
CONCAT(drivers.name, " ", drivers.surname) as driver,
drivers.id as driver_id
FROM drives, drivers WHERE drives.driver = drivers.id
AND drives.timestamp > DATE_SUB(now(), INTERVAL 12 MONTH) ORDER BY drives.timestamp Asc

但是,如果一个月没有记录,则它不会按预期包含在结果集中,我正在使用 php 进行大量计算以完成我想要的。

我的问题是:有没有办法检索一个简单的结果集,其中包含过去 12 个月每个月的驱动器总和,如果一个月有 0 个驱动器,则它也必须包含在结果中显示设置。

最佳答案

您需要对包含每个月的行的表进行外连接。假设您没有这样的表,您可以使用硬编码的 UNION 查询即时创建它:

SELECT * FROM
(SELECT DATE_FORMAT(now(), "%b") as Month
UNION
SELECT DATE_FORMAT(now() - INTERVAL 1 MONTH), "%b")
UNION
SELECT DATE_FORMAT(now() - INTERVAL 2 MONTH), "%b")
UNION
...
SELECT DATE_FORMAT(now() - INTERVAL 11 MONTH), "%b")) AS Months
LEFT JOIN (SELECT DATE_FORMAT(drives.timestamp, "%b") AS Month,
drives.timestamp,
DATE_FORMAT(drives.timestamp, "%d-%m-%Y %H:%i:%s") AS Exact_date,
drives.departure,
drives.destination,
drives.route,
CONCAT(drivers.name, " ", drivers.surname) as driver,
drivers.id as driver_id
FROM drives, drivers WHERE drives.driver = drivers.id
AND drives.timestamp > DATE_SUB(now(), INTERVAL 12 MONTH)) data
ON Months.Month = data.Month
ORDER BY data.timestamp

任何没有记录的月份的数据列中都会有一行 NULL

关于Mysql 近12个月按月记录总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19757458/

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