As I read the question this would help you very much on the way.
There are a couple of things you can do to improve this tho:
- Create separate table with hours to avoid the unions (or do it with numbers table);
- Store times separatly, the TIME() method slows the query.
.
SELECT
hours.`hour`,
COUNT(occurrence.perfId) AS occurrences
FROM (
SELECT '00:00' AS `hour`
UNION SELECT '01:00'
UNION SELECT '02:00'
UNION SELECT '03:00'
UNION SELECT '04:00'
UNION SELECT '05:00'
UNION SELECT '06:00'
UNION SELECT '07:00'
UNION SELECT '08:00'
UNION SELECT '09:00'
UNION SELECT '10:00'
UNION SELECT '11:00'
UNION SELECT '12:00'
UNION SELECT '13:00'
UNION SELECT '14:00'
UNION SELECT '15:00'
UNION SELECT '16:00'
UNION SELECT '17:00'
UNION SELECT '18:00'
UNION SELECT '19:00'
UNION SELECT '20:00'
UNION SELECT '21:00'
UNION SELECT '22:00'
UNION SELECT '23:00'
) hours
LEFT JOIN YOUR_TABLE occurrence ON hours.`hour` BETWEEN TIME(occurrence.Entry_time) AND TIME(occurrence.Exit_time)
GROUP BY hours.`hour`
ORDER BY occurrences DESC
Would produce (Data from a test database):
[hour] [occurrences]
10:00 73554
11:00 67492
09:00 65679
08:00 63886
13:00 63565
12:00 62525
07:00 61500
14:00 53095
15:00 49017
16:00 41955
17:00 31991
18:00 21251
06:00 17591
19:00 13717
20:00 8532
21:00 4421
22:00 2050
23:00 818
05:00 796
04:00 561
01:00 175
03:00 123
02:00 120
00:00 23
To get the hour only just wrap with a query and select the first:
SELECT hour FROM (
# Paste query from above here...
) hourData
LIMIT 1;