我有以下查询,根据过去12个月的ToxicologyTests获得总结果,即使该月有零。
/articles/:year?/:month?/:day?
即使存在零,也会正确输出每月的测试次数。在过去的12个月到过去的30天里,我一直在努力改变这一点,如果当天没有测试的话,我也会保持零。有什么建议吗?
SELECT y, m, Count(ToxicologyTests.receiveDate) as count
FROM (
SELECT y, m
FROM (
SELECT YEAR(CURDATE()) y
UNION ALL SELECT YEAR(CURDATE())-1) years,
(
SELECT 1 m
UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4
UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8
UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
) months
) ym
LEFT JOIN ToxicologyTests
ON ym.y = YEAR(ToxicologyTests.receiveDate)
AND ym.m = MONTH(ToxicologyTests.receiveDate)
WHERE (
y=YEAR(CURDATE())
AND m<=MONTH(CURDATE())
)
OR (
y<YEAR(CURDATE())
AND m>MONTH(CURDATE())
)
GROUP BY y, m
答案 0 :(得分:0)
你能试试这个查询吗?我已经改变了WHERE子句:
SELECT y, m, Count(ToxicologyTests.receiveDate) as count
FROM (
SELECT y, m
FROM
(SELECT YEAR(CURDATE()) y UNION ALL SELECT YEAR(CURDATE())-1) years,
(SELECT 1 m UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4
UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8
UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12) months) ym
LEFT JOIN ToxicologyTests
ON ym.y = YEAR(ToxicologyTests.receiveDate)
AND ym.m = MONTH(ToxicologyTests.receiveDate)
WHERE ToxicologyTests.receiveDate BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()
GROUP BY y, m