My original query is as follows:
SELECT COUNT(*) AS count, YEAR(created_at) AS "year", MONTH(created_at) AS "month"
FROM quotes WHERE
(YEAR(created_at) = YEAR(CURDATE()) AND MONTH(created_at) = MONTH(CURDATE())
OR YEAR(created_at) = YEAR(CURDATE()) AND MONTH(created_at) = MONTH(CURDATE()) -1)
AND status_id = 1
GROUP BY YEAR(created_at), MONTH(created_at) DESC
This query basically retrieves the COUNT
for this month and the previous month and works fine except when there are no results for either month.
I have two similar queries that do the same except for weeks and years.
I've tried to use COALESCE
and IFNULL
but it doesn't seem to include NULL
results.
SELECT IFNULL(COUNT(*), 0) AS count, YEAR(created_at) AS "year", MONTH(created_at) AS "month"
FROM quotes
WHERE
(YEAR(created_at) = YEAR(CURDATE()) AND MONTH(created_at) = MONTH(CURDATE()) OR YEAR(created_at) = YEAR(CURDATE()) AND MONTH(created_at) = MONTH(CURDATE()) -1)
AND status_id = 1
GROUP BY YEAR(created_at), MONTH(created_at) DESC
Actual Result
count | year | month
-----------------------
1 | 2014 | 11
Expected Result
count | year | month
-----------------------
1 | 2014 | 11
0 | 2014 | 10