如何将一个 table 的计数除以另一个所需的计数或其他解决方案

How to divide count from one table by the count from the other one or other solution needed

我只有一个 table 列:

id date
1  2020-03-01 16:34:00
1  2020-03-01 17:33:32
2  2020-03-02 15:40:54

id为特定日期登录网站的客户。他们每天可以登录多次。我需要每天计算保留率。即超过一次登录的用户数除以当天所有用户数!所以输出应该是这样的:

date         retention
2020-03-01   33%
2020-03-02   35%
2020-03-03   29%

我用过:

select tbl.date, count(tbl.device_id)/count(distinct(retention_cohort.device_id)) as cnt from
    (select date_trunc('day', session_time) as date, device_id from retention_cohort
    group by date, device_id
    having count(device_id)>1
    order by date) tbl
group by tbl.date

但是这个带计数的除法不起作用。请帮忙!

number of users who logged in more than once divided by all users within that day

您可以使用两个聚合级别来执行此操作:首先计算每个用户和每天的登录次数,然后计算大于 1 的计数比率。

select session_date, avg((cnt > 1)::int) retention_rate
from (
    select date_trunc('day', session_time) session_date, count(*) cnt
    from retention_cohort
    group by session_date, device_id
) t
group by session_date