MySql Query: include days that have COUNT(id) == 0 but only in the last 30 days

↘锁芯ラ 提交于 2020-02-21 14:32:49

问题


I am doing a query to get the number of builds per day from our database for the last 30 days. But it has become needed to marked days where there were no builds also.

In my WHERE clause I use submittime to determine whether there were builds, how could I modify this to include days that have COUNT(id) == 0 but only in the last 30 days.

Original Query:

   SELECT COUNT(id) AS 'Past-Month-Builds', 
          CONCAT(MONTH(submittime), '-', DAY(submittime)) as 'Month-Day' 
     FROM builds 
    WHERE DATE(submittime) >= DATE_SUB(CURDATE(), INTERVAL 30 day) 
 GROUP BY MONTH(submittime), DAY(submittime);

What I've Tried:

   SELECT COUNT(id) AS 'Past-Month-Builds', 
          CONCAT(MONTH(submittime), '-', DAY(submittime)) as 'Month-Day' 
     FROM builds 
    WHERE DATE(submittime) >= DATE_SUB(CURDATE(), INTERVAL 30 day) 
       OR COUNT(id) = 0
 GROUP BY MONTH(submittime), DAY(submittime);

回答1:


You need a table of dates, then left join to the builds table.

Something like this:

SELECT 
    COUNT(id) AS 'Past-Month-Builds', 
    CONCAT(MONTH(DateTable.Date), '-', DAY(DateTable.Date)) as 'Month-Day' 
FROM DateTable
    LEFT JOIN builds ON DATE(builds.submittime) = DateTable.Date
WHERE DateTable.Date >= DATE_SUB(CURDATE(), INTERVAL 30 day) 
GROUP BY MONTH(submittime), DAY(submittime);


来源:https://stackoverflow.com/questions/6845775/mysql-query-include-days-that-have-countid-0-but-only-in-the-last-30-days

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!