您好我有以下查询来获取每月在12个月的时间窗口内发生的驱动器。但是结果不正确,例如在我的测试数据库中,2月份只发生了3个驱动器,但在我的结果集中显示了9个驱动器。
SELECT mlist.m, count(data.month) as drvs
FROM users, (
SELECT 'Jan' AS m
UNION SELECT 'Feb' AS m
UNION SELECT 'Mar' AS m
UNION SELECT 'Apr' AS m
UNION SELECT 'May' AS m
UNION SELECT 'Jun' AS m
UNION SELECT 'Jul' AS m
UNION SELECT 'Aug' AS m
UNION SELECT 'Sep' AS m
UNION SELECT 'Oct' AS m
UNION SELECT 'Nov' AS m
UNION SELECT 'Dec' AS m
) AS mlist LEFT JOIN (SELECT DATE_FORMAT(drives.timestamp, '%b') AS month,
drives.timestamp,
CONCAT(drivers.name, ' ', drivers.surname) as driver,
drivers.id as driver_id
FROM drives, drivers WHERE drives.user = '146'
AND drives.timestamp > DATE_SUB(now(), INTERVAL 12 MONTH)) data
ON mlist.m = data.month GROUP BY mlist.m
结果:
“四月”, “3” “月”, “3” “DEC”, “6” “二月”, “9” “月”, “3” “月”, “3” “君”, “3” “月”, “3” “5月3日” “月”, “3” “月”, “6” “月”, “3”
答案 0 :(得分:0)
这有效:
SELECT mlist.m, count(data.drive_id) AS drvs
FROM users, (
SELECT 'Jan' AS m
UNION SELECT 'Feb' AS m
UNION SELECT 'Mar' AS m
UNION SELECT 'Apr' AS m
UNION SELECT 'May' AS m
UNION SELECT 'Jun' AS m
UNION SELECT 'Jul' AS m
UNION SELECT 'Aug' AS m
UNION SELECT 'Sep' AS m
UNION SELECT 'Oct' AS m
UNION SELECT 'Nov' AS m
UNION SELECT 'Dec' AS m
) AS mlist LEFT JOIN (SELECT DATE_FORMAT(drives.timestamp, '%b') AS month,
drives.id AS drive_id,
drives.timestamp
FROM drives WHERE drives.user = '146'
AND drives.timestamp > DATE_SUB(now(), INTERVAL 12 MONTH)) data
ON mlist.m = data.month GROUP BY mlist.m