Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 不返回没有记录的月份的月份组_Mysql_Sql_Group By - Fatal编程技术网

Mysql 不返回没有记录的月份的月份组

Mysql 不返回没有记录的月份的月份组,mysql,sql,group-by,Mysql,Sql,Group By,我有一个问题: select c.MonthNo,c.YearNo from (SELECT month(created_at) as MonthNo, Year(created_At) as YearNO, count(*) as total FROM users u where created_at between '2014-02-01 00:00:00' and '2015-01-06 23:59:59'

我有一个问题:

select c.MonthNo,c.YearNo 
from (SELECT month(created_at) as MonthNo,
             Year(created_At) as YearNO,
             count(*) as total
      FROM users u 
      where created_at between '2014-02-01 00:00:00' and '2015-01-06 23:59:59' 
      group by monthNo order by yearNO,monthNo) as c;
结果是:

MonthNo  |  YearNo
---------+--------
  2      |  2014
  3      |  2014
  4      |  2014
  5      |  2014
  6      |  2014
  7      |  2014
  8      |  2014
  9      |  2014
  10     |  2014      
  11     |  2014
  12     |  2014
我的问题是查询没有返回当前月份,即2015年1月。我想是因为它没有任何记录。在这种情况下,我希望它返回0。

创建日历表


这有关系吗?为什么不干脆不返回当月的任何记录?@Charnjeet-我现在在CTE检查中错过了maxrecursion。
WITH calender
     AS (SELECT Cast('20140101' AS DATE) AS [dates] -- startdate
         UNION ALL
         SELECT Dateadd(dd, 1, [dates])
         FROM   calender
         WHERE  Dateadd(dd, 1, [dates]) <= '20151231' -- Endate
        )
SELECT Month(c.dates) AS MonthNo,
       Year(c.dates)  AS YearNO,
       Count(*)       AS total
FROM   calender C
       LEFT JOIN users u
              ON Month(c.dates) = Month(created_at)
                 AND Year(c.dates) = Year(created_at)
WHERE  created_at BETWEEN '2014-02-01 00:00:00' AND '2015-01-06 23:59:59'
GROUP  BY Month(c.dates),
          Year(c.dates)
ORDER  BY Month(c.dates),
          Year(c.dates)
OPTION (maxrecursion 0)