Home:ALL Converter>MySQL query to group results by hour of day, taking into account daylight savings

MySQL query to group results by hour of day, taking into account daylight savings

Ask Time:2013-04-04T23:08:20         Author:AntonChanning

Json Formatter

I have a report that uses a an sql query similar to this:

SELECT HOUR(somedatetime) AS hour, COUNT(*) AS count
FROM table
GROUP BY HOUR(surveyenddatetime)

I've simplified it here by leaving out the where clause that can limit the results to a given time period. It works quite nicely for getting the total records grouped by hour of day they were entered for the time period selected.

However, it has one fatal flaw. When the time period selected includes records not in the same 'timezone' as the user running the report, such as records from before daylight savings and records after daylight savings, it doesn't work. All records are stored in GMT/UTC on in the datetime fields and converted to local times in php via the web front end. But this query runs before any of that happens and php has no way of knowing what the original dates where for the totals grouped into each hour.

Is there a way I can solve this query to take daylight savings into account using just a MySQL query or am I going to have to do something more complicated?

Author:AntonChanning,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/15815020/mysql-query-to-group-results-by-hour-of-day-taking-into-account-daylight-saving
yy