mysql月统计数据,没有的填充为0

要按时间戳字段按月份分组查询记录表,可以使用DATE_FORMAT函数将时间戳字段格式化为年月格式,然后将结果按照该字段进行分组。

SELECT a.month month,ifnull(b.count, 0) count FROM (
      SELECT 1 month UNION ALL 
      SELECT 2 month UNION ALL 
      SELECT 3 month UNION ALL 
      SELECT 4 month UNION ALL
      SELECT 5 month UNION ALL 
      SELECT 6 month UNION ALL 
      SELECT 7 month UNION ALL 
      SELECT 8 month UNION ALL 
      SELECT 9 month UNION ALL
      SELECT 10 month UNION ALL 
      SELECT 11 month UNION ALL 
      SELECT 12 month
    ) a LEFT JOIN
    (
     	SELECT DATE_FORMAT(FROM_UNIXTIME(`create_time`), '%m') AS `month`, COUNT(*) AS `count`
FROM user_log
GROUP BY `month`
    ) b
    ON a.month=b.month ORDER BY month

mysql月统计数据,没有的填充为0_第1张图片

你可能感兴趣的:(mysql,数据库)