题解 | #每月及截止当月的答题情况#

每月及截止当月的答题情况

https://www.nowcoder.com/practice/1ce93d5cec5c4243930fc5e8efaaca1e

题目:

请输出自从有用户作答记录以来,每月的试卷作答记录中月活用户数、新增用户数、截止当月的单月最大新增用户数、截止当月的累积用户数。结果按月份升序输出。

知识点:

sum() over(order by 字段):累计求和

代码:

新增用户数:先求出该用户的首次登录月份,再汇总每个月的uid,就是这个月新增登陆的uid【高赞】

SELECT
	start_month,
	mau,
	month_add_uv,
	max(month_add_uv) over(ORDER BY start_month) max_month_add_uv,
	sum(month_add_uv) over(ORDER BY start_month) cum_sum_uv
from(
    SELECT
        start_month,
        count(DISTINCT uid) mau,
        count(DISTINCT case when start_month=first_month then uid else null end)as month_add_uv#每月增加用户
    from 
        (select *
                ,date_format(start_time,"%Y%m") as start_month
                ,min(date_format(start_time,"%Y%m")) over(partition by uid order by date_format(start_time,"%Y%m")) as first_month
                from exam_record) t
        GROUP BY start_month) t1

下面是错误的,新增用户数不等于这个月的用户数-上个月的用户数,如果旧用户这个月不活跃的话,那就会漏掉新用户数,

如:1月份用户是1001,1002,二月份用户1003,1004,两个月用户活跃数都是为2,但是新增用户数也都为2.

所以这样写是不对的。

可能以后重新刷的时候还会犯错,所以记录一下。

SELECT
	start_month,
	mau,
	month_add_uv,
	max(month_add_uv) over(order by start_month) max_month_add_uv,
	sum(month_add_uv) over(order by start_month) cum_sum_uv
from(
		SELECT 
		start_month,
		mau,
		if(mau >lag(mau, 1, 0) over(ORDER BY start_month),mau - lag(mau, 1, 0) over(ORDER BY start_month), 0) 		month_add_uv 
        /*如果1月份用户是1001,1002,二月份用户1003,1004,两个月用户活跃数都是为2,但是新增用户数也都为2.
        所以这样写是不对的。
		*/from (
			SELECT 
				DATE_FORMAT(start_time,'%Y%m') start_month,
				count(distinct uid) mau
			FROM
				exam_record
			GROUP BY DATE_FORMAT(start_time,'%Y%m')
			ORDER BY start_month)t) t1

全部评论

相关推荐

点赞 评论 收藏
分享
zYvv:双一流加大加粗再标红,然后广投。主要是获奖荣誉不够,建议开始不用追求大厂,去别的厂子刷下实习。
点赞 评论 收藏
分享
醉蟀:你不干有的是人干
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

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