2021年11月每天的人均浏览文章时长

明确题意:

统计2021年11月每天的人均浏览文章时长(秒数),结果保留1位小数,并按时长由短到长排序


问题分解:

  • 计算每次文章浏览的时长和日期:
    • 过滤目标时间窗的有效浏览记录:WHERE artical_id != 0 AND DATE_FORMAT(in_time, "%Y%m") = "202111"
    • 将进入时间转化为日期:DATE(in_time) as dt
    • 计算浏览时长:TIMESTAMPDIFF(SECOND, in_time, out_time) as view_len_sec
  • 按日期分组:GROUP BY dt
  • 计算人均时长(=总时长÷人数):SUM(view_len_sec) / COUNT(DISTINCT uid) as avg_view_len_sec
  • 保留1位小数:ROUND(x, 1)

细节问题:

  • 表头重命名:as
  • 按时长由短到长排序:ORDER BY avg_view_len_sec

完整代码:

SELECT dt, ROUND(SUM(view_len_sec) / COUNT(DISTINCT uid), 1) as avg_view_len_sec
FROM (
    SELECT uid, DATE(in_time) as dt,
        TIMESTAMPDIFF(SECOND, in_time, out_time) as view_len_sec
    FROM tb_user_log
    WHERE artical_id != 0 AND DATE_FORMAT(in_time, "%Y%m") = "202111"
) as t_uid_len
GROUP BY dt
ORDER BY avg_view_len_sec;