我原來的查詢如下:包括NULL結果爲0,在MySQL
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
該查詢基本檢索COUNT
本月與上月持平,當有對任何一個月沒有結果,除了正常工作。
我有兩個類似的查詢,做相同的幾周和幾年除外。
我試過使用COALESCE
和IFNULL
,但它似乎沒有包含NULL
的結果。
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
實際結果
count | year | month
-----------------------
1 | 2014 | 11
預期結果
count | year | month
-----------------------
1 | 2014 | 11
0 | 2014 | 10
你嘗試移動'你的聚集函數裏面IFNULL'? – 2014-11-25 13:37:09
@ jbarker2160 nope,不是100%確定你的建議,但我有一個想法,並會試一試 – martincarlin87 2014-11-25 13:40:36
你不能選擇不存在的東西。您必須以某種方式創建或模擬丟失的數據。 – Strawberry 2014-11-25 13:46:47