I have a table that has a START_DATE and an END_DATE column.
I want to retrieve the average time difference between these timestamps for each hour, but only between the hours of 9AM to 6PM, over the course of the last few days. I’d like the output to look like this:
elapsed hour
-------------
2.5 11 <--today at 11AM
1.7 10
2.4 9
1.9 18 <--this is yesterday
2.4 17
4.0 16
I believe I am quite close, but I just can’t get the code to work. Here is what I have:
SELECT
TRUNCATE(AVG(TIME_TO_SEC(TIMEDIFF(END_DATE, START_DATE))/60), 2) as elapsed,
EXTRACT(HOUR FROM END_DATE) as hour
FROM
TIME_INFO
WHERE
EXTRACT(HOUR FROM END_DATE) BETWEEN 9 AND 18 AND
DATE(END_DATE) > CURDATE() - INTERVAL 3 DAY
GROUP BY
EXTRACT(HOUR FROM END_DATE)
ORDER BY
END_DATE DESC
It is close, but only returns what I want from three days ago instead of across days like I’d like. I am using mySQL 5.0, anyone have any ideas?
If you want multiple days you will need the day as well as hour in the
GROUP BYclause. Currently it’s averaging all the values for the same hour on multiple days. (Values for today’s 11, yesterday’s 11, etc., are averaged together)I don’t have an easy way to test it, but something like:
If you want it to work across month/year boundaries you’ll probably want
DATE(END_DATE)rather than theEXTRACT(DAY FROM END_DATE), in which case output might look something like: