1. 程式人生 > >SQL SERVER 查詢每日新增使用者數量、次留數量

SQL SERVER 查詢每日新增使用者數量、次留數量

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 日期;

結果如下: