简体   繁体   中英

Select date from hourly date range for a 24 hour day

I need to do a report. The report tracks where a user clicks on a terminal over time these clicks are stored on 2 tables in a DB. I need to find an elegant solution to loop over the date ranges and do the report for every hour of the day.

I am stuck with the best and most way elegant to loop over the hours (the report will show hours from 00:00 until 23:00 even if there are no clicks recorded for that hour).

so my output needs to be (as an example)

00:00   -   34 clicks
01:00   -   22 clicks
02:00   -   91 clicks
03:00   -   4  Clicks
...
...
23:00   -  17  Clicks

I was thinking of declaring 2 variables in PHP $startHour = 00:00; $endHour = $startHour + 01:00;

And doing a loop incrementing the $startHour unitl it matched the end hour, but I dont know if I can increment the hour variables like this.

The dates are stored in this format: 2012-11-22 09:17:29

Here is my mysql query:

SELECT tbl_xboxstats.sessionend_date, 
       tbl_xboxstatsaux.XboxStatsId, 
       tbl_xboxstatsaux.ItemId, 
       tbl_xboxstats.UnitId, 
       tbl_xboxstats.UIId, 
       WEEK( tbl_xboxstats.sessionend_date ) AS WeekNumber, 
       Count(tbl_xboxstatsaux.ItemId) AS Count
FROM tbl_xboxstats
INNER JOIN tbl_xboxstatsaux ON tbl_xboxstats.id = tbl_xboxstatsaux.XboxStatsId
WHERE tbl_xboxstats.sessionend_date
BETWEEN '2012-11-22 "' . $startHour . '"'
AND '2012-11-22"' . $endHour . '"'
GROUP BY tbl_xboxstatsaux.XboxStatsId
LIMIT 0 , 30

I don't get how the two tables are related (you stated the output must be hour + clicks but the query select a lot of fields) but if you want to show the clicks grouped by hours try something like:

SELECT EXTRACT(HOUR FROM sessionend_date) AS hour, COUNT(*) 
  FROM your_table
 WHERE DATE(sessionend_date) = '2012-11-22'
 GROUP BY hour;

This will group all of your results by the hour.

SELECT tbl_xboxstats.sessionend_date, 
       tbl_xboxstatsaux.XboxStatsId, 
       tbl_xboxstatsaux.ItemId, 
       tbl_xboxstats.UnitId, 
       tbl_xboxstats.UIId, 
       WEEK( tbl_xboxstats.sessionend_date ) AS WeekNumber, 
       HOUR( tbl_xboxstats.sessionend_date ) AS Hours
       Count(tbl_xboxstatsaux.ItemId) AS Count
FROM tbl_xboxstats
INNER JOIN tbl_xboxstatsaux ON tbl_xboxstats.id = tbl_xboxstatsaux.XboxStatsId
WHERE tbl_xboxstats.sessionend_date
BETWEEN '2012-11-22 "' . $startHour . '"
AND '2012-11-22"' . $endHour . '"
GROUP BY Hours
LIMIT 0 , 30

I think the safest way may be to convert your start date to a timestamp, add 3600 to it (1 hour), and then reconvert it into a date format.

Alternatively you might want to use strtotime to add an hour:

$starttime = "01:00";

$endtime = strtotime($starttime, "+1 hour")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM