题解 | #牛客每个人最近的登录日期(五)#

牛客每个人最近的登录日期(五)

http://www.nowcoder.com/practice/ea0c56cd700344b590182aad03cc61b8

  1. 查询出有新用户登录的日期以及登录人数
select date,(select count(*) 
                 from (select min(user_id),date
                       from login 
                       group by user_id) as t
                 where t.date = l.date
                ) as new_counts
    from login l
    group by date
    order by date) as table1
date count
2020-10-12 3
2020-10-13 0
2020-10-14 1
2020-10-15 0
  1. 查询出每个日期新用户次日继续登录的人数
select count(*) as new
       from (select min(user_id),date
              from login 
              group by user_id) as t
              where t.date = DATE_ADD(l.date,INTERVAL 1 DAY)
名称 缩写
2020-10-12 2
2020-10-13 0
2020-10-14 1
2020-10-15 0
select l.date,(select count(*) 
                from login l1
                where (user_id,DATE_ADD(l1.date,INTERVAL 1 DAY)) in (select user_id,date from login )
               and l1.date = l.date) as counts
 from login l
 group by date) as table2
  1. 由于除数不能为0,所以用case语句判断如果当天没有新用户登录,所以该日的新用户留存率也就为0。
select table1.date,
                    case table1.new_counts
                    when 0 then 0.000
                    else round(table2.counts / table1.new_counts, 3)
                    end as p
from 
    (select date,(select count(*) 
                 from (select min(user_id),date
                       from login 
                       group by user_id) as t
                 where t.date = l.date
                ) as new_counts
    from login l
    group by date
    order by date) as table1
,
	(select l.date,(select count(*) 
                	from login l1
                	where (user_id,DATE_ADD(l1.date,INTERVAL 1 DAY)) in (select user_id,date from login )
                	and l1.date = l.date) as counts

from login l
group by date) as table2
where table1.date = table2.date
order by date;
全部评论
CREATE TABLE `login` ( `id` int(4) NOT NULL, `user_id` int(4) NOT NULL, `client_id` int(4) NOT NULL, `date` date NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `login` VALUES (1,2,1,'2020-10-12'),(2,3,2,'2020-10-12'),(3,1,2,'2020-10-12'),(4,2,2,'2020-10-13'),(5,1,2,'2020-10-13'),(6,5,2,'2020-10-13'),(7,3,1,'2020-10-14'),(8,4,1,'2020-10-14'),(9,5,1,'2020-10-14'),(10,1,1,'2020-10-14'),(11,4,1,'2020-10-15'); 试下这组数据,第二天留存率是2.sql有问题
点赞 回复 分享
发布于 2022-06-17 11:40

相关推荐

用微笑面对困难:你出于礼貌叫了人一声大姐,大姐很欣慰,她真把你当老弟
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

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