每期独特的新用户

时间:2017-08-09 16:44:12

标签: sql postgresql distinct

在psql中,我编写了一个查询,每周返回唯一用户

COUNT(DISTINCT user_id)

但是,我也有兴趣计算每周唯一新用户的数量,换句话说,就是之前几周从未活跃过的用户。

如何在postgresql中编写此查询?

当前查询:

SELECT  TO_CHAR(date_trunc('week', start_time::date), 'YYYY-MM-DD') 
AS weekly, COUNT(*) AS total_transactions, COUNT(DISTINCT user_id) AS unique_users 
FROM transactions 
GROUP BY  weekly ORDER BY  weekly

1 个答案:

答案 0 :(得分:0)

使用min获取user_id的第一次出现。用它来计算每周的唯一身份用户。您可能还希望在年份中包含分组。

select 
TO_CHAR(date_trunc('week', first_appearance), 'YYYY-MM-DD') AS weekly, 
COUNT(*) AS total_transactions,
COUNT(DISTINCT user_id) AS unique_users
from (SELECT t.*,
      MIN(start_time::date) OVER(PARTITION BY user_id) AS first_appearance
      FROM transactions t
     ) t
GROUP BY weekly