1、创建用户新增表和登录日志表:
--用户新增表
create table new_user
(id int identity(1,1),
uid varchar(20),
regist_time datetime)
insert into new_user(uid,regist_time) values
('18-1104','2018-03-05 03:46:53'),
('18-1105','2018-03-11 09:46:53'),
('18-1106','2018-03-18 09:22:53')
--登录日志表
create table login_log
(id int identity(1,1),
uid varchar(20),
update_time datetime)
insert into login_log(uid,update_time) values
('18-1101','2018-03-05 09:46:53'),
('18-1101','2018-03-06 09:46:53'),
('18-1101','2018-03-06 09:56:53'),
('18-1102','2018-03-15 09:56:53'),
('18-1102','2018-03-16 09:56:53'),
('18-1103','2018-03-19 09:56:53')
表格如下:
2、查询用户每日新增数量、次留数量(新增的用户在第二天登录的用户数量)
select 日期
,sum(新增) as 新增
,sum(次留) as 次留
from
(select convert(varchar(20),regist_time,111) as 日期
,count(uid) as 新增
,0 as 次留
from new_user
group by convert(varchar(20),regist_time,111)
union all
select convert(varchar(20),a.regist_time,111) as 日期
,0 as 新增
,count(distinct case when convert(varchar(20),b.update_time,111) = convert(varchar(20),dateadd(day,1,a.regist_time),111) then a.uid else NULL end) as 次留
from new_user a inner join login_log b on a.uid = b.uid
group by convert(varchar(20),a.regist_time,111)) as x
group by 日期;
结果如下: