Yottagray
Yottagray

Reputation: 2592

SQL: Avg Per Hour, Between Times, Over Several Days

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?

Upvotes: 3

Views: 1789

Answers (1)

Tim Sylvester
Tim Sylvester

Reputation: 23168

If you want multiple days you will need the day as well as hour in the GROUP BY clause. 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:

SELECT 
    TRUNCATE(AVG(TIME_TO_SEC(TIMEDIFF(END_DATE, START_DATE))/60), 2) as elapsed,
    EXTRACT(DAY FROM END_DATE) as day,
    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(DAY FROM END_DATE),
    EXTRACT(HOUR FROM END_DATE)
ORDER BY 
    END_DATE DESC

If you want it to work across month/year boundaries you'll probably want DATE(END_DATE) rather than the EXTRACT(DAY FROM END_DATE), in which case output might look something like:

elapsed  date        hour
------------------------- 
2.5      2011/03/25  11 <--today at 11AM
1.7      2011/03/25  10
2.4      2011/03/25  9
1.9      2011/03/24  18 <--this is yesterday
2.4      2011/03/24  17
4.0      2011/03/24  16

Upvotes: 3

Related Questions