SQL162. 2021年11月每天的人均浏览文章时长
描述
id | uid | artical_id | in_time | out_time | sign_cin |
1 | 101 | 9001 | 2021-11-01 10:00:00 | 2021-11-01 10:00:31 | 0 |
2 | 102 | 9001 | 2021-11-01 10:00:00 | 2021-11-01 10:00:24 | 0 |
3 | 102 | 9002 | 2021-11-01 11:00:00 | 2021-11-01 11:00:11 | 0 |
4 | 101 | 9001 | 2021-11-02 10:00:00 | 2021-11-02 10:00:50 | 0 |
5 | 102 | 9002 | 2021-11-02 11:00:01 | 2021-11-02 11:00:24 | 0 |
dt | avg_viiew_len_sec |
2021-11-01 | 33.0 |
2021-11-02 | 36.5 |
示例1
输入:
DROP TABLE IF EXISTS tb_user_log; CREATE TABLE tb_user_log ( id INT PRIMARY KEY AUTO_INCREMENT COMMENT '自增ID', uid INT NOT NULL COMMENT '用户ID', artical_id INT NOT NULL COMMENT '视频ID', in_time datetime COMMENT '进入时间', out_time datetime COMMENT '离开时间', sign_in TINYINT DEFAULT 0 COMMENT '是否签到' ) CHARACTER SET utf8 COLLATE utf8_bin; INSERT INTO tb_user_log(uid, artical_id, in_time, out_time, sign_in) VALUES (101, 9001, '2021-11-01 10:00:00', '2021-11-01 10:00:31', 0), (102, 9001, '2021-11-01 10:00:00', '2021-11-01 10:00:24', 0), (102, 9002, '2021-11-01 11:00:00', '2021-11-01 11:00:11', 0), (101, 9001, '2021-11-02 10:00:00', '2021-11-02 10:00:50', 0), (102, 9002, '2021-11-02 11:00:01', '2021-11-02 11:00:24', 0);
输出:
2021-11-01|33.0 2021-11-02|36.5
Mysql 解法, 执行用时: 36ms, 内存消耗: 6368KB, 提交时间: 2022-01-25
select date_format(in_time,"%Y-%m-%d")dt, round (sum(timestampdiff(second,in_time,out_time))/count(distinct uid),1)avg_view_len_sec from tb_user_log where month(in_time)= 11 and artical_id !=0 group by dt order by avg_view_len_sec
Mysql 解法, 执行用时: 36ms, 内存消耗: 6404KB, 提交时间: 2021-12-08
select DATE_FORMAT(in_time,'%Y-%m-%d') as a, round(sum(TIMESTAMPDIFF(second,in_time,out_time))/count(distinct uid),1) as b from tb_user_log where year(in_time)=2021 and month(in_time)=11 and artical_id!=0 group by a order by b ;
Mysql 解法, 执行用时: 36ms, 内存消耗: 6416KB, 提交时间: 2022-01-25
select date_format(in_time,'%Y-%m-%d') dt, round(sum(timestampdiff(second,in_time,out_time)) /count(distinct uid),1) avg_view_len_sec from tb_user_log where date_format(in_time,'%Y-%m')='2021-11' and artical_id != 0 group by dt order by avg_view_len_sec
Mysql 解法, 执行用时: 36ms, 内存消耗: 6416KB, 提交时间: 2021-12-08
select dt,round(sum(sc)/count(distinct uid),1) avg_view_len_sec from (select uid,date(out_time) dt,TIMESTAMPDIFF(SECOND,in_time,out_time) sc,artical_id from tb_user_log) t where year(dt) = "2021" and month(dt) = "11" and artical_id != 0 group by dt order by avg_view_len_sec ;
Mysql 解法, 执行用时: 36ms, 内存消耗: 6424KB, 提交时间: 2022-02-10
-- 人均浏览文章时长 timestampdiff(second,out_time,in_time) select left(in_time,10)as dt, round(sum(timestampdiff(second,in_time,out_time))/count(distinct uid),1) as avg_view_len_sec from tb_user_log where artical_id<>0 and in_time like '2021-11%' group BY dt order by avg_view_len_sec