如何按user_id和action_type分组统计用户各操作类型总耗时?
问题描述
现有如下表结构及数据:
| id | user_id | action_type | action_start_time | action_end_time |
|---|---|---|---|---|
| 1 | 5 | 4 | 2023-06-21 16:52:49.111 | 2023-06-21 16:55:49.022 |
| 2 | 3 | 6 | 2023-06-21 16:55:51.052 | 2023-06-21 17:10:19.100 |
| 3 | 5 | 4 | 2023-06-21 18:38:44.062 | 2023-06-21 18:59:51.025 |
| 4 | 16 | 1 | 2023-06-21 19:52:39.426 | 2023-06-21 20:01:49.127 |
| 5 | 5 | 1 | 2023-06-21 20:11:19.321 | 2023-06-21 21:55:49.132 |
需要计算每个用户在每种action_type上花费的总时间,目前已能使用DATEDIFF函数计算单条记录的耗时秒数:
SELECT DATEDIFF(SECOND, action_start_time, action_end_time) AS TotalSeconds from my_table;
但不清楚如何按user_id和action_type进行分组统计。
解决方案
通过GROUP BY子句对user_id和action_type分组,搭配SUM()函数累加每组的耗时即可实现需求:
SELECT user_id, action_type, SUM(DATEDIFF(SECOND, action_start_time, action_end_time)) AS TotalSeconds FROM my_table GROUP BY user_id, action_type ORDER BY user_id, action_type;
关键说明:
GROUP BY user_id, action_type:将数据按用户ID、操作类型双重维度分组,保证同一用户的同类型操作记录被归为一组SUM(...):对每组内的单条记录耗时求和,得到该用户该操作的总耗时ORDER BY:可选配置,用于让结果按用户ID、操作类型排序,提升可读性
执行上述SQL后,会得到如下结果:
| user_id | action_type | TotalSeconds |
|---|---|---|
| 3 | 6 | 868 |
| 5 | 1 | 6269 |
| 5 | 4 | 1327 |
| 16 | 1 | 549 |
内容的提问来源于stack exchange,提问作者pileup
相关产品推荐
相关产品推荐

