繁体   English   中英

使用PostgreSQL计算日常用户的保留

[英]Calculate retention for daily users with PostgreSQL

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

table1具有user_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');

table2具有user_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天的结果

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

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会更合适。

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

您正在将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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM