I’m trying to count entries grouped per hour.
I’ve found some useful info inform on different sites and here on: MySQL Group By Hours
But the result is not what I’ve expected.
With the following code I get:
SELECT CONCAT(Hour, ':00-', Hour+1, ':00') AS Hours,
COUNT(`usage_time`) AS `usage` FROM `usage`
RIGHT JOIN (
SELECT 0 AS Hour
UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3
UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6
UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15
UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18
UNION ALL SELECT 19 UNION ALL SELECT 20 UNION ALL SELECT 21
UNION ALL SELECT 22 UNION ALL SELECT 23
) AS AllHours ON HOUR(`usage_time`) = Hour
WHERE `usage_function` LIKE 'PlayedWholeSong' AND `usage_date` = DATE_SUB(CURDATE(), INTERVAL 0 DAY) OR `usage_time` IS NULL
GROUP BY Hour
ORDER BY Hour
Result:
Hours usage
2:00-3:00 0
4:00-5:00 6
6:00-7:00 2
8:00-9:00 3
9:00-10:00 20
10:00-11:00 1
14:00-15:00 14
15:00-16:00 1
16:00-17:00 32
17:00-18:00 10
As these are entry’s from today, I don’t have any entries after 19:00.
Also I don’t see an entry from 00:00 – 01:00, 03:00 – 04:00 and several others are missing.
But I do want to show a list with every 24 hour and the result, even if there’s nothing.
String thing is the result shows a 0 between 02:00 – 03:00.
I’ve learned a lot today about mysql, but nothing that solves my issue.
I hope you can learn me something, doesn’t have to be code, a direction would be great.
I prefer
LEFT JOINoverRIGHT JOINpersonally. That way you can add yourWHEREcriteria in yourJOINand it won’t constrict your results. Try this:Here is a simplified SQL Fiddle.
Good luck.