MySQL show count of 0 for dates with no records

前端 未结 2 1938
被撕碎了的回忆
被撕碎了的回忆 2021-01-15 16:02

I\'m trying to get the COUNT of all users attempts by a list of the current week (last 7 days)

This query works but doesnt return 0 if the day not exist:

         


        
2条回答
  •  北海茫月
    2021-01-15 16:04

    Create a calendar table or you could try:

    SELECT COUNT(*) AS attempt_count,
           DATE_FORMAT(ca_date,'%Y/%m/%d') AS attempt_date
    FROM
      (SELECT STR_TO_DATE('2014/06/19', '%Y/%m/%d') ca_date
       UNION ALL SELECT STR_TO_DATE('2014/06/18', '%Y/%m/%d') ca_date
       UNION ALL SELECT STR_TO_DATE('2014/06/17', '%Y/%m/%d') ca_date
       UNION ALL SELECT STR_TO_DATE('2014/06/16', '%Y/%m/%d') ca_date
       UNION ALL SELECT STR_TO_DATE('2014/06/15', '%Y/%m/%d') ca_date
       UNION ALL SELECT STR_TO_DATE('2014/06/14', '%Y/%m/%d') ca_date
       UNION ALL SELECT STR_TO_DATE('2014/06/13', '%Y/%m/%d') ca_date) AS calendar
    LEFT JOIN users_attempts ON users_attempts.attempt_date = calendar.ca_date
    GROUP BY calendar.ca_date
    ORDER BY calendar.ca_date DESC;
    

提交回复
热议问题