如何计算接收方和发送方之间的平均应答时间?

How to calculate average time of answer between reciever and sender?

我有一个 table message_conversation:

id | conversation_id | reciever_id | sender_id | message | created_at
______________________________________________________________________
1   1                   1             2            A         2018-08-01
2   1                   2             1            B         2018-08-02

我需要获取对话消息之间 sender_id = 2 的平均回答时间。

我这样试过:

SELECT 
 id, created_at 
FROM 
  message_conversation 
WHERE 
  sender_id = 2 OR receiver_id = 2 
GROUP BY conversation_id, created_at
ORDER BY id LIMIT 2

结果我预计 2018-08-02 - 2018-08-01 天、小时、分钟

我们可以使用 UNIX_TIMESTAMP() 计算秒数差异,然后 SEC_TO_TIME() 将平均差异转换回时间格式。这只适用于 mySQL 8,所以我后来添加了第二种方法。

  • 对于MySQL 8.0
create table message_conversation (
  id int,
  conversation_id int,
  receiver_id int,
  sender_id int,
  message char(2),
  created_at date
  );
insert into message_conversation values
(1,   1,                   1,             2,            'A',         '2018-08-01'),
(2,   1,                   2,             1,            'B',         '2018-08-02');
with reply_time as
(select
  sender_id,
  conversation_id,
  UNIX_TIMESTAMP(created_at) 
  - UNIX_TIMESTAMP( lag(created_at) over 
                      (partition by conversation_id 
             order by created_at)
  ) as diff_seconds
  from message_conversation
)
select 
  SEC_TO_TIME(avg(coalesce(diff_seconds,0))) time_diff
from reply_time
where coalesce(diff_seconds,0) > 0
and sender_id = 1 ;
| time_diff     |
| :------------ |
| 24:00:00.0000 |

db<>fiddle here

  • 对于 mySQL 5 岁及以下
set @prev = '3000-01-01 00:00:00';
set @conv = 0;
select
  sec_to_time(avg(seconds_diff)) average_difference
from
(select
  case when conversation_id = @conv then
     TIMESTAMPDIFF(
    SECOND,
    @prev,
    created_at
    ) end seconds_diff,
  @conv := conversation_id,
  @prev := created_at
from message_conversation) a
where coalesce(seconds_diff,0) > 0;

| average_difference | | :----------------- | | 24:00:00.0000 |

db<>fiddle here

  • 1 个特定版本 sender_id