我想获得部门的平均响应时间。
以下是我的数据库架构。 门票:
| ID | Subject | Department | AdminId | ClientId | created_at |
| 1 | Test1 | 1 | 0 | 1 | 2015-01-01 10:10:10 |
| 2 | Test2 | 1 | 0 | 2 | 2015-01-01 20:20:20 |
TicketReplies:
--AuthorType:
----1 => Admin
----2 => Client
| ID | TicketId | Body | AuthorId | AuthorType | created_at |
| 1 | 1 | Test Body? | 1 | 2 | 2015-01-01 10:10:10 |
| 2 | 1 | Yes! | 1 | 1 | 2015-01-01 10:48:16 |
| 3 | 2 | Are you Ok? | 2 | 2 | 2015-01-01 20:20:20 |
| 4 | 2 | Yes! | 1 | 1 | 2015-01-02 08:15:18 |
答案 0 :(得分:0)
平均响应时间是最大时间减去最小值除以响应总数减去1。
以秒为单位获取值:
select t.department,
( (to_seconds(max(created_at)) - to_seconds(min(created_at)) ) /
nullif(count(*) - 1, 0)
)
from ticketreplies tr join
tickets t
on tr.ticketid = t.id
group by t.department;
这适用于MySQL 5.5+。在早期版本中,您可以通过转换为Unix时间戳来执行相同的操作。
答案 1 :(得分:0)
<强> SqlFiddleDemo 强>
SELECT Department, AVG(response_time) as avg_response -- in seconds
FROM
(
SELECT T.Department,
TR.TicketId,
TIMESTAMPDIFF(SECOND, MIN(TR.created_at), MAX(TR.created_at)) as response_time
FROM Tickets T
JOIN TicketReplies TR
ON T.id = TR.TicketId
GROUP BY T.Department, TR.TicketId
) as T
GROUP BY Department
<强>输出强>
| Department | avg_response |
|------------|--------------|
| 1 | 22592 |