1

您好,我有这个查询来获取在 1 年前的时间窗口中特定月份发生的驱动器列表。

SELECT COUNT( drives.id ) AS drives, DATE_FORMAT( drives.timestamp,  '%d-%m-%Y' ) AS mdate
FROM drives, users
WHERE drives.user = '146'
AND DATE_FORMAT( drives.timestamp,  '%b' ) =  'Feb'
AND drives.timestamp > DATE_SUB(now(), INTERVAL 12 MONTH) 
GROUP BY DATE(drives.timestamp) ORDER BY drives.timestamp ASC

我得到以下结果:

drives  mdate
1       14-02-2013
2       17-02-2013

但是,即使没有找到该日期的记录,我也想要该月的每个日期的结果,并在没有驱动器发生的日期旁边显示 0。对我来说棘手的部分是如何获取特定日期的确切日期一年前的时间窗口中的一个月。我可以用 php 实现它,但我更喜欢更清洁的解决方案。

4

1 回答 1

0

不确定用户表的位置(您正在交叉加入它,但实际上并未在任何地方使用它),但是这样的事情应该可以满足您的要求(未经测试)。

SELECT Sub1.aDay, COUNT( drives.id ) AS drives
FROM
(
    SELECT DATE_ADD('2013-02-01', INTERVAL units.i + tens.i * 10 DAY) AS aDay
    FROM
    (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
    CROSS JOIN
    (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
    HAVING MONTH(aDay) = 2
) Sub1
LEFT OUTER JOIN drives
ON Sub1.aDay = DATE(drives.timestamp)
WHERE drives.user = '146'
GROUP BY DATE(drives.timestamp) 
ORDER BY drives.timestamp ASC
于 2013-11-04T13:33:45.213 回答