题解 | #SQL17 平均活跃天数和月活人数#

平均活跃天数和月活人数

http://www.nowcoder.com/practice/9e2fb674b58b4f60ac765b7a37dde1b9

明确题意:

计算2021年每个月里试卷作答区用户平均月活跃天数avg_active_days和月度活跃人数mau


问题分解:

  • 筛选2021年活跃的用户作答记录:where submit_time is not NULL and YEAR(submit_time)='2021'
  • 获取用户-活跃日期的去重结果:select distinct uid, DATE_FORMAT(submit_time, "%Y%m%d") as ymd
  • 统计每个月的平均活跃天数和月活人数:
    • 按月份分组:提取月份SUBSTR(ymd, 1, 6) as month;分组group by month
    • 统计月活人数:count(distinct uid) as mau
    • 统计平均活跃天数:总活跃人天数除以活跃人数count(1) / count(distinct uid)

细节问题:

  • 表头重命名:as
  • 平均活跃天数保留2位小数:round(..., 2)

完整代码:

select SUBSTR(ymd, 1, 6) as `month`,
    round(count(1) / count(distinct uid), 2) as avg_active_days,
    count(distinct uid) as mau
from (
    select distinct uid, DATE_FORMAT(submit_time, "%Y%m%d") as ymd
    from exam_record
    where submit_time is not NULL and YEAR(submit_time)='2021'
) as t_active_day
group by `month`
SQL进阶 文章被收录于专栏

SQL进阶step by step

全部评论
为什么uid在子查询里面去了重,还要再外面distinct uid?
1 回复 分享
发布于 2022-03-06 20:28
请教一下 select distinct uid, DATE_FORMAT(submit_time, "%Y%m%d") as ymd中 两列的行数应该不一样吧?这样也可以输出吗?
1 回复 分享
发布于 2021-12-10 21:53
想问下代码第二行里面的count(1) 是啥意思,跪求楼主解答!
1 回复 分享
发布于 2021-10-25 17:19
group by 的执行顺序不是在select之前嘛,为什么month是在select时定义的,group by就可以直接拿来用
1 回复 分享
发布于 2021-12-04 21:52
请问,distinct uid, DATE_FORMAT(submit_time, "%Y%m%d") 是同时对这两字段一起去重吗,没有明白怎么同时对两列去重?
1 回复 分享
发布于 2022-03-24 17:04
请大佬帮忙看看,为啥我的这段代码一直报错: select substring(ymd, 1, 6) as 'month', round(count(1) / count(distinct uid),2) as avg_active_days, count(distinct uid) as mau from( select distinct uid,date_format(submit_time,"%y%m%d") as ymd from exam_record where submit_time is not null and year(submit_time)='2021' ) as a group by 'month'
点赞 回复 分享
发布于 2024-09-12 20:36 北京
大佬,有个小疑问? 在MySQL中,group by的执行顺序不是在 select 之前吗? 你这里代码好像不用管这个
点赞 回复 分享
发布于 2024-06-27 08:52 重庆
select case when start_time like '2021-01%' then '202101' when start_time like '2021-02%' then '202102' when start_time like '2021-03%' then '202103' when start_time like '2021-04%' then '202104' when start_time like '2021-05%' then '202105' when start_time like '2021-06%' then '202106' when start_time like '2021-07%' then '202107' when start_time like '2021-08%' then '202108' when start_time like '2021-09%' then '202109' when start_time like '2021-10%' then '202110' when start_time like '2021-11%' then '202111' when start_time like '2021-12%' then '202112' else end as act_month, count(uid)/count(act_month),count(uid) from exam_record group by month; 大佬我这个为啥报错
点赞 回复 分享
发布于 2022-03-16 14:21
year函数可以直接在where子句中使用吗,where子句后不可跟聚合函数,year函数不算聚合函数,所以可以使用?
点赞 回复 分享
发布于 2022-03-11 20:01
请问 submit_time is not NULL 这个条件可以省略吗
点赞 回复 分享
发布于 2022-01-24 16:01
请问这个用子查询不会影响查询的速度吗?
点赞 回复 分享
发布于 2021-11-26 14:48

相关推荐

点赞 评论 收藏
分享
评论
29
8
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务