计算两个时间戳之间的不同日期
Count distinct dates between two timestamps
我想计算用户活跃的 % 天。像这样的查询
select
a.id,
a.created_at,
CURRENT_DATE - a.created_at::date as days_since_registration,
NOW() as current_d
from public.accounts a where a.id = 3257
returns
id created_at days_since_registration current_d tot_active
3257 2022-04-01 22:59:00.000 1 2022-04-02 12:00:0.000 +0400 2
此人在不到24小时前(不到一天前)注册,但注册和现在之间有两个不同的日期。因此,如果用户在午夜前一小时和午夜后一小时处于活动状态,则他在不到一天的时间内活跃了两天(活跃天数的 200%)
两个小时前在 23:00:00 注册的用户计算不同日期并得到 2 的正确方法是什么?
WITH cte as (
SELECT 42 as userID,'2022-04-01 23:00:00' as d
union
SELECT 42,'2022-04-02 01:00:00' as d
)
SELECT
userID,
count(d),
max(d)::date-min(d)::date+1 as NrOfDays,
count(d)/(max(d)::date-min(d)::date+1) *100 as PercentageOnline
FROM cte
GROUP BY userID;
输出:
userid
count
nrofdays
percentageonline
42
2
2
100
我想计算用户活跃的 % 天。像这样的查询
select
a.id,
a.created_at,
CURRENT_DATE - a.created_at::date as days_since_registration,
NOW() as current_d
from public.accounts a where a.id = 3257
returns
id created_at days_since_registration current_d tot_active
3257 2022-04-01 22:59:00.000 1 2022-04-02 12:00:0.000 +0400 2
此人在不到24小时前(不到一天前)注册,但注册和现在之间有两个不同的日期。因此,如果用户在午夜前一小时和午夜后一小时处于活动状态,则他在不到一天的时间内活跃了两天(活跃天数的 200%)
两个小时前在 23:00:00 注册的用户计算不同日期并得到 2 的正确方法是什么?
WITH cte as (
SELECT 42 as userID,'2022-04-01 23:00:00' as d
union
SELECT 42,'2022-04-02 01:00:00' as d
)
SELECT
userID,
count(d),
max(d)::date-min(d)::date+1 as NrOfDays,
count(d)/(max(d)::date-min(d)::date+1) *100 as PercentageOnline
FROM cte
GROUP BY userID;
输出:
userid | count | nrofdays | percentageonline |
---|---|---|---|
42 | 2 | 2 | 100 |