1

I have one query that I'm testing times with.

I get two different times and this is making me doubt the correctness of my data.

Here are the two examples :

SELECT 
    users.fname as counselor,
    count(session.anum) as students,
    SEC_TO_TIME(AVG(TIME_TO_SEC(TIMEDIFF(starttime, signintime)))) AS 'AVG Wait Time',
    SEC_TO_TIME(AVG(TIME_TO_SEC(TIMEDIFF(finishtime, starttime)))) AS 'AVG Session Length'
FROM session
    LEFT JOIN support 
        ON support.session_id = session.session_id
    LEFT JOIN users 
        ON users.username = support.counselor
WHERE session.status = 3 
GROUP BY fname;

This returns :

00:01:17 and 00:00:05

the next query is :

SELECT 
    users.fname as counselor,
    count(session.anum) as students,
    SEC_TO_TIME(AVG(TIMEDIFF(starttime, signintime))) AS 'AVG Wait Time',
    SEC_TO_TIME(AVG(TIMEDIFF(finishtime, starttime))) AS 'AVG Session Length'
FROM session
    LEFT JOIN support 
        ON support.session_id = session.session_id
    LEFT JOIN users 
        ON users.username = support.counselor
WHERE session.status = 3 
GROUP BY fname;

00:01:37 and 00:00:05

Why does this happen and which result set am I supposed to trust? Would love if any one can clear my confusion.

1 Answer 1

3

TIMEDIFF() returns a string, e.g.

TIMEDIFF('13:07:33', '9:5:37') -> 04:01:56

If you average that directly, mysql will try to cast 04:01:56 to an int and end up with avg(04) instead.

which is why you have to time_to_sec, which returns that time value as a simple int: 14516, which CAN be averaged directly.

Sign up to request clarification or add additional context in comments.

6 Comments

Ah, so the TIME_TO_SEC version of the query is the most reliable? Would it be best to use TIMESTAMPDIFF() instead?
This is true. AVG() is used with an int. This takes all numbers that come before an non-number characters and removes everything after them. Example would be 123!456 -> 123. Good job Marc.
While I wait to accept the answer, would it be best to use TIMESTAMPDIFF()
easiest method is AVG(unix_timestamp(start) - unix_timestamp(end)). that'll convert the datetimes DIRECTLY to plain "seconds" (ints).
Might seem like a stupid remark but would it be smart to use unix_timestamp / SEC_TO_TIME(AVG(TIME_TO_SEC(TIMEDIFF()))) on all my time differences?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.