【场景】:每天人均

【分类】:嵌套子查询、日期函数、month、year、date、date_format

分析思路

难点:

1.难点:计算人均浏览时长时,可能一个人当天浏览多条记录,所以需要对用户去重后统计个数

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

​ [条件]:where artical_id <> '0' and month(in_time) = 11 and year(in_time) = 2021

​ [使用]:group by dt;order by avg_viiew_len_sec;年月日使用date();两个日期相减得到秒使用timestampdiff(second,expr1,expr2)

最终结果

select 查询结果 [日期;人均浏览文章时长]
from 从哪张表中查询数据 [用户行为日志表]
where 查询条件 [2021年11月;文章ID不为0]
group by 分组条件 [日期]
order by 对查询结果排序 [时长升序];

求解代码

方法一:

使用month、year、date

select
    date(in_time) as dt,
    round(sum(timestampdiff(second,in_time,out_time))/count(distinct uid),1) as avg_viiew_len_sec
from tb_user_log
where artical_id != 0
and month(in_time) = 11
and year(in_time) = 2021
group by dt
order by avg_viiew_len_sec

方法二:

使用date_format、date

select
    date(in_time) as dt,
    round(sum(timestampdiff(second,in_time,out_time))/count(distinct uid),1) as avg_viiew_len_sec
from tb_user_log
where artical_id != 0
and date_format(in_time,'%Y%m') = '202111'
group by dt
order by avg_viiew_len_sec