使用PostgreSQL计算每日用户的保留率

时间:2016-05-30 08:30:36

标签: sql postgresql metrics pgadmin retention

我正在尝试使用pgadminIII / postgresql计算用户登录会话的每日保留时间。

table1user_idfirst_login_datelast_login_date

CREATE TABLE table1 (user_id numeric, first_login_date date, last_login_date date);

  INSERT INTO table1 (user_id, first_login_date, last_login_date) VALUES (12346, '2010-06-01', '2010-06-02'),
(67890, '2010-03-01', '2010-03-10'),
(67890, '2010-03-01', '2010-03-10'),
(90123, '2010-08-01', '2010-08-15'),
(45678, '2010-08-01', '2010-08-20'),
(76543, '2010-07-01', '2010-07-01');

table2user_idsession_idlogin_date

CREATE TABLE table2 (user_id numeric, session_id numeric, login_date date);

INSERT INTO table2 (user_id, session_id, login_date) VALUES
(12346, '8764', '2010-06-02'),
(67890, '4657', '2010-03-05'),
(90123, '3945', '2010-08-09'),
(45678, '20845', '2010-08-02'),
(67890, '29384', '2010-03-07'),
(90123, '3424', '2010-08-12'),
(45678, '349284', '2010-08-10');

table1中有一些重复项。 因此,我不确定我的计算具有2天保留和5天保留的用户的查询是否正确。

我用于2天的查询是:

SELECT table1.user_id, first_login_date, table2.login_date,
(table2.login_date - table1.first_login_date) as datediff, FROM table1
JOIN table2 ON table2.user_id = table2.user_id WHERE
(table2.login_date - table1.first_login_date) = 1;

为7位用户提供2天保留的结果

但是,如果我添加distinct子句,例如:

SELECT distinct table1.user_id, first_login_date, table2.login_date,
    (table2.login_date - table1.first_login_date) as datediff FROM table1
    JOIN table2 ON table2.user_id = table2.user_id WHERE
    (table2.login_date - table1.first_login_date) = 1;

我得到3位用户的结果,保留2天。

关于日常保留的计算,我咨询了HEREHEREHERE,我不确定我的技术是否给了我正确的结果。例如,要计算DAU,self-join是否更合适。

鉴于table1table2中的数据是我使用我定义的查询准确的2天保留结果吗? 是否有优化的方法来计算此保留期?

1 个答案:

答案 0 :(得分:1)

您正在加入table2自己:

ON table2.user_id = table2.user_id

在子查询中执行distinct

select distinct on (t2.login_date)
    user_id,
    first_login_date,
    t2.login_date,
    t2.login_date - t1.first_login_date as datediff
from
    (
        select distinct *
        from t1
    ) t1
    inner join
    t2 using (user_id)
where t2.login_date - t1.first_login_date = 1
 user_id | first_login_date | login_date | datediff 
---------+------------------+------------+----------
   12346 | 2010-06-01       | 2010-06-02 |        1
   45678 | 2010-08-01       | 2010-08-02 |        1