数据准备
drop table Activity;
Create table If Not Exists Activity (player_id int, device_id int, event_date date, games_played int);
Truncate table Activity;
insert into Activity (player_id, device_id, event_date, games_played) values ('1', '2', '2016-03-01', '5');
insert into Activity (player_id, device_id, event_date, games_played) values ('1', '2', '2016-03-02', '6');
insert into Activity (player_id, device_id, event_date, games_played) values ('2', '3', '2017-06-25', '1');
insert into Activity (player_id, device_id, event_date, games_played) values ('3', '1', '2016-03-02', '0');
insert into Activity (player_id, device_id, event_date, games_played) values ('3', '4', '2018-07-03', '5');
输入
输出
with t1 as (
select *,
lag(event_date,1) over (partition by player_id) rn1
from Activity
),t2 as (
select distinct player_id
from Activity
group by player_id
),t3 as (
select count(player_id) as sum_total
from t2
),t4 as (
select player_id,
datediff(event_date,rn1) rn2
from t1
where datediff(event_date,rn1)=1
group by player_id, datediff(event_date,rn1)
)
select round(t4.rn2 / t3.sum_total, 2) fraction
from t4,t3
where 1=1
;