按月分组,如果未找到数据,则返回0

时间:2013-12-02 00:38:27

标签: mysql

我一直在努力修复我的查询几天:(。 它应该按月分组,如果没有找到记录则返回0。 一个例子:

    SELECT MONTH(created_at) AS month_num, 
DATE_FORMAT(created_at, '%b') AS month_name, COUNT(*) AS total_num 
    FROM table WHERE user_id=1384249399168
    GROUP BY MONTH(created_at) ORDER BY created_at DESC

结果:

month_num       month_name       total_num
     8            Aug                 20 
     7            Jul                 15
     5            May                 39
     2            Feb                 10
     1            Jan                 8

预期结果:

month_num       month_name       total_num
         12           Dec                 0
         11           Nov                 0
         10           Oct                 0
         9            Sep                 0
         8            Aug                 20 
         7            Jul                 15
         6            Jun                 0
         5            May                 39
         4            Apr                 0
         3            Mar                 0
         2            Feb                 10
         1            Jan                 8

我已经尝试了很多答案,尤其是MySql count() to return 0 if no records found,但没有成功。

请帮忙吗?

2 个答案:

答案 0 :(得分:2)

我没有测试过但它应该可以工作:

SELECT MONTH(created_at) AS month_num, 
DATE_FORMAT(created_at, '%b') AS month_name, ifnull(count(*),0) AS total_num 
    FROM table WHERE user_id=1384249399168
    GROUP BY MONTH(created_at) ORDER BY created_at DESC

答案 1 :(得分:1)

这篇文章解决了我的问题。 我不得不创建一个包含所有12个月的表格。

mysql select the count of records for every month 特别感谢@Turdaliev