Counting problem

since you have a numbers table already (How to count number of dates base on usage - #17 by r937), we can use it here to get all the hourly intervals

you could theoretically also apply the same technique to span your range of dates, but for now i’ll just simply use all dates in the table

SELECT dates.thedate , CONCAT(RIGHT(CONCAT('0',numbers.n,':00'),5) ,' - ' ,RIGHT(CONCAT('0',numbers.n+1,':00'),5)) AS time_slot , COUNT(activelogs.start_time) AS thecount FROM numbers CROSS JOIN ( SELECT DISTINCT DATE(start_time) AS thedate FROM activelogs ) AS dates LEFT OUTER JOIN activelogs ON DATE(activelogs.start_time) = dates.thedate AND TIME(activelogs.start_time) >= RIGHT(CONCAT('0',numbers.n,':00'),5) AND TIME(activelogs.start_time) < RIGHT(CONCAT('0',numbers.n+1,':00'),5) WHERE numbers.n BETWEEN 0 AND 23 GROUP BY dates.thedate , time_slot

the reason i asked about what application language you’re using is because this query doesn’t do the “crosstab” or “pivot” layout, you can simply do that with arrays in php

1 Like