Average Time to Reply to Message

梦想与她 提交于 2019-12-06 21:36:44

Your question is well formulated but leaves room for interpretation. This is one interpretation:

SELECT avg(TIMESTAMPDIFF(SECOND, c.c_date, a.a_date) AS avg_time_to_response
FROM   (
    SELECT ref, min(date) AS c_date
    FROM   tbl
    WHERE  client > 0
    GROUP  BY 1
    ) c
JOIN  (
    SELECT ref, min(date) AS a_date
    FROM   tbl
    WHERE  admin > 0
    GROUP  BY 1
    ) a USING (ref)
WHERE a.a_date > c.c_date;

Gives you the average time that passes between the first client posting and the first admin posting per thread (message reference number).

Unanswered messages are ignored. Threads started by Admins would confuse the result with negative durations, so I excluded those. Only the first response time per thread goes into the result. Additional postings on the same thread are ignored here.

Read the manual here about TIMESTAMPDIFF().
Thanx to @MrJ and @Vincent for pointing out the mistake with the subtraction of timestamps!

Concerning GROUP BY 1

I quote the manual here:

Columns selected for output can be referred to in ORDER BY and GROUP BY clauses using column names, column aliases, or column positions. Column positions are integers and begin with 1:

Emphasis mine. So I group on the first column that is selected (ref in both cases). Just a notational shortcut.

Needless to say, I hate working with MySQL :

SELECT AVG(delay_answer)
FROM (SELECT MIN(delay_answer) AS delay_answer
      FROM (SELECT M1.ref, client, admin, TIMESTAMPDIFF(SECOND, date_original, date) AS delay_answer
            FROM messages M1
            INNER JOIN (SELECT ref, MIN(date) AS date_original
                        FROM messages
                        GROUP BY ref) M2
            ON M1.ref = M2.ref AND date > date_original
            WHERE admin <> 0 AND client = 0) x
      GROUP BY ref) y;

This returns the average time (in seconds) that it took for an admin to answer a message (created by anyone, not necessarily a client, but this can easily be changed).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!