统计新用户和返回的用户数

7cwmlq89  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(317)

我有一张这样的table:

我想找到每月的新客户数(cust\u id)(如首次发现的记录)和下个月回来的客户数(例如,2016年3月的第一个记录,而此cust\u id在2016年4月有记录)。第三栏我想计算回来的用户的百分比。
例子:

+--------------------+-----------+----------------+------------+
| month_registration | new_users | returned_users | percentage |
+--------------------+-----------+----------------+------------+
| March, 2016        |        36 |             12 |       0.33 |
| April, 2016        |        44 |             11 |       0.25 |
| May, 2016          |        50 |              5 |        0.1 |
+--------------------+-----------+----------------+------------+
niwlg2el

niwlg2el1#

可以使用窗口函数:

select date_trunc('month', ship_date),
       count(distinct custid) filter (where date_trunc('month', first_ship_date) = date_trunc('month', ship_date)) as new_customers,
       count(distinct custid) filter (where date_trunc('month', first_ship_date) < date_trunc('month', ship_date)) as returning_customers,
       ( count(distinct custid) filter (where date_trunc('month', first_ship_date) < date_trunc('month', ship_date)) * 1.0 /
         count(distinct custid) filter (where date_trunc('month', first_ship_date) = date_trunc('month', ship_date))
       ) as ratio    
from (select t.*, min(ship_date) over (partition by custid) as first_ship_date
      from t
     ) t
group by date_trunc('month', ship_date)

相关问题