mysql - MySQL计算一天内第一个初始收到的消息和第一个答案之间的平均时间
问题描述
我有三个名为chats
、chat_members
和的表chat_messages
。我想在一天内获得第一个初始收到的消息和第一个答案之间的平均时间。
聊天成员
|chat_id|user_id|
-----------------
| 1 | 3 |
| 1 | 4 |
| 2 | 3 |
| 2 | 6 |
聊天消息
|chat_id|sender_id| body | created_at |
------------------------------------------------------|
| 1 | 4 |"initial 1 "|2019-06-30 10:31:16 |
| 1 | 3 |"answer day 1"|2019-06-30 10:52:56 |
| 2 | 6 |"initial ans" |2019-06-30 10:54:33 |
| 2 | 3 |"answer" |2019-06-30 10:56:30 |
| 1 | 4 |"initial 2" |2019-07-01 09:30:02 |
| 1 | 3 |"answer day 2"|2019-07-01 09:45:02 |
预期结果:特定用户的平均响应时间。假设user_id: 3
有平均响应时间17.5 minutes
。
|chat_id|avg_minutes|
--------------------|
| 1 | 20 |
| 2 | 15 |
将其视为 Facebook 页面的平均响应时间:
“响应时间是您的主页在一天内对新消息发送初始响应所需的平均时间。”</p>
解决方案
这是一个中间答案...
DROP TABLE IF EXISTS chat_messages;
CREATE TABLE chat_messages
(message_id SERIAL PRIMARY KEY
,chat_id INT NOT NULL
,sender_id INT NOT NULL
,body VARCHAR(255) NOT NULL
,created_at DATETIME NOT NULL
);
INSERT INTO chat_messages VALUES
(1,1,4,'initial 1','2019-06-30 10:31:16'),
(2,1,3,'answer day 1','2019-06-30 10:52:56'),
(3,2,6,'initial ans','2019-06-30 10:54:33'),
(4,2,3,'answer','2019-06-30 10:56:30'),
(5,1,4,'initial 2','019-07-01 09:30:02'),
(6,1,3,'answer day 2','2019-07-01 09:45:02');
SELECT x.*
, y.sender_id responder
, MIN(y.created_at) response
FROM chat_messages x
JOIN chat_messages y
ON y.chat_id = x.chat_id
AND y.created_at > x.created_at
AND y.sender_id <> x.sender_id
GROUP
BY x.message_id,y.sender_id;
+------------+---------+-----------+-------------+---------------------+-----------+---------------------+
| message_id | chat_id | sender_id | body | created_at | responder | response |
+------------+---------+-----------+-------------+---------------------+-----------+---------------------+
| 1 | 1 | 4 | initial 1 | 2019-06-30 10:31:16 | 3 | 2019-06-30 10:52:56 |
| 3 | 2 | 6 | initial ans | 2019-06-30 10:54:33 | 3 | 2019-06-30 10:56:30 |
| 5 | 1 | 4 | initial 2 | 0019-07-01 09:30:02 | 3 | 2019-06-30 10:52:56 |
+------------+---------+-----------+-------------+---------------------+-----------+---------------------+
这给了我们每个响应者最早响应的时间。
接下来,我们可以汇总 created_at 和 response 之间的差异,但我将把它作为练习留给读者。
推荐阅读
- email - 管理员如何配置 GSuite 用户邮箱签名
- apache-flink - 如果单个任务管理器崩溃,是否应该重新启动整个集群?
- pandas - 转换输入字符串:未列出?
- laravel - Laravel 队列未从 Kernel.php 读取更新
- slack-api - 在频道中最后一条消息的 4 个月后归档松弛频道
- c# - HashSet 是否保留插入顺序*如果没有项目被删除*
- vue.js - 如何将 OpenStreetMap 添加到我的 NUXT 应用程序
- python - 从python中的列表中获取一个单词
- python - 如何在 Python 中仅捕获某种类型的 ValueError?
- angular - 过滤表的工具栏