0

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

table1user_id, first_login_date,last_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_id, session_id,login_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更合适。

给定数据,table1使用table2我定义的查询,我的 2 天保留结果是否准确?是否有一种优化的方法来计算这种保留?

4

1 回答 1

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
于 2016-05-30T13:15:45.133 回答