小编典典

MySQL最近12个月中按月记录的总数

sql

您好,我正在使用此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个驱动器,则还必须将其包含在结果集中显示。


阅读 171

收藏
2021-04-28

共1个答案

小编典典

您需要使用一个表进行外部联接,该表每个月包含一行。假设您没有这样的表,则可以使用硬编码的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在数据列中都会有一行。

2021-04-28