这是我的activities
桌子。
activities
+----+---------+----------+-----------------+
| id | user_id | activity | log_time |
+----+---------+----------+-----------------+
| 6 | 1 | start | 12 Oct, 1000hrs |
| 2 | 1 | task | 12 Oct, 1010hrs |
| 7 | 1 | task | 12 Oct, 1040hrs |
| 3 | 1 | start | 12 Oct, 1600hrs |
| 1 | 1 | task | 12 Oct, 1610hrs |
| 9 | 1 | start | 14 Oct, 0800hrs |
| 10 | 1 | start | 16 Oct, 0900hrs |
| 4 | 1 | task | 16 Oct, 0910hrs |
| 8 | 2 | start | 12 Oct, 1000hrs |
| 5 | 2 | task | 12 Oct, 1020hrs |
+----+---------+----------+-----------------+
我需要用户在所有会话中花费的总时间。每个会话在一天内发生,包括一个“开始”和多个“任务”(在下一个会话以“开始”开始之前)。一个会话持续时间 = 最后一个任务 - 开始 [时间戳差异]
output
+---------+------------+------------------------------------------------+
| user_id | total_time | This is explanation (not a column) |
+---------+------------+------------------------------------------------+
| 1 | 60 | 12_Oct[40+10] + 14_Oct[0] + 16_Oct[10] = 60min |
| 2 | 20 | 12_Oct[20] = 20min |
+---------+------------+------------------------------------------------+
我无法弄清楚如何获得会话中的最后一个任务。我已经尝试了基本的聚合和连接查询 - 但它不起作用。
作为一种方法,我认为我真正需要的是以某种方式获取最后一列(低于/ session_group),然后我可以聚合并获得最大/最小时间戳之间的差异。
+----+---------+----------+-----------------+---------------+
| id | user_id | activity | log_time | session_group |
+----+---------+----------+-----------------+---------------+
| 6 | 1 | start | 12 Oct, 1000hrs | 1 |
| 2 | 1 | task | 12 Oct, 1010hrs | 1 |
| 7 | 1 | task | 12 Oct, 1040hrs | 1 |
| 3 | 1 | start | 12 Oct, 1600hrs | 2 |
| 1 | 1 | task | 12 Oct, 1610hrs | 2 |
| 9 | 1 | start | 14 Oct, 0800hrs | 3 |
| 10 | 1 | start | 16 Oct, 0900hrs | 4 |
| 4 | 1 | task | 16 Oct, 0910hrs | 4 |
| 8 | 2 | start | 12 Oct, 1000hrs | 5 |
| 5 | 2 | task | 12 Oct, 1020hrs | 5 |
+----+---------+----------+-----------------+---------------+
请让我知道是否甚至可以通过 sql (MySQL) 获得所需的输出以及如何去做?或者是否有必要通过 Javascript 循环遍历数据?
下面是表的 MySQL 查询:
create table activities (
id INT NOT NULL,
user_id INT NULL,
activity VARCHAR(45),
log_time DATETIME NOT NULL DEFAULT NOW(),
PRIMARY KEY(id))
ENGINE = InnoDB;
insert into activities
(id, user_id, activity, log_time)
values
(6,1,'start', '2021-10-12 10:00:00'),
(2,1,'task' , '2021-10-12 10:10:00'),
(7,1,'task' , '2021-10-12 10:40:00'),
(3,1,'start', '2021-10-12 16:00:00'),
(1,1,'task', '2021-10-12 16:10:00'),
(9,1,'task', '2021-10-14 08:00:00'),
(10,1,'start','2021-10-16 09:00:00'),
(4,1,'task', '2021-10-16 09:10:00'),
(8,2,'start', '2021-10-12 10:00:00'),
(5,2,'task', '2021-10-12 10:20:00');