Skip to content
Advertisement

MySQL Group By Hours

I’m trying to get a report from my history table by hourly usage. history table is;

I want to group by HOUR and COUNT all records in a given date range.

I used a query something like this but it doesn’t display all hours.

It displays only if there are any records.

Advertisement

Answer

Your existing query can be reduced to:

To display every hour, including those for which there is no data, you need to outer join with a table containing all the hours for which you want data. You can build such a table in your query using UNION:

However, the treatment of groups for which no data exists is really a matter for business logic that’s best placed in your data access layer rather than in the database itself: indeed it should be trivial for your application to use a zero value whenever an hour is absent.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement