选择上个月的记录,如果特定时间窗口中没有记录,则显示0

时间:2013-11-04 12:43:54

标签: mysql sql

您好我有这个查询来获取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。对我来说,棘手的部分是如何获得确切的日期具体月份在1年后的时间窗口。 我可以用php实现这个,但我更喜欢更清洁的解决方案。

1 个答案:

答案 0 :(得分: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